#!/usr/bin/env python
# coding: utf-8
import time
from wxbot import *
import requests
import os,re,string,sys,time
import cookielib
import random
import md5
"百度爬图的微信接口"
url = "http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word="
#获得页面所有图片的链接
def get_pic_links(url):
req = requests.get(url)
html = req.text
links = re.findall(r'"thumbURL":"(.*?.jpg)"', html) #小图
sourcelinks = re.findall(r'"objURL":"(.*?)"', html) #原图
return links, sourcelinks
#使用wget下载
def wget_pic(u, name):
referer = re.findall(r'//(.*?)/',u)[0]
command = 'wget --referer="%s" -O "%s" "%s"'%(referer, name, u)
print "Command is: %s"%(command)
os.system(command)
class MyWXBot(WXBot):
def handle_msg_all(self, msg):
if msg['msg_type_id'] == 4 and msg['content']['type'] == 0:
user_input = msg["content"]["data"]
user_input = user_input.encode("utf-8") #Unicode => str
#m = md5.new()
#m.update(user_input)
#md5name = m.hexdigest()
md5name = random_str(10)
name = ''.join([md5name, '.jpg'])
#name = name.encode("utf-8") #Unicode => str
urls, sourceurls = get_pic_links(url+ user_input)
if len(urls)<1:
self.send_msg_by_uid(u'并没有搜到啥', msg['user']['id'])
return 0
else:
self.send_msg_by_uid(u'请稍等', msg['user']['id'])
i = 0
while i < 20:
i = i + 1;
if not os.path.exists(name):
num = random.randint(1,len(urls)-1)
#下载图片,命名为name
try:
headers = {
"User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:45.0) Gecko/20100101 Firefox/45.0",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
referer = re.findall(r'//(.*?)/',urls[num])[0]
headers["referer"] = referer
r = requests.get(urls[num], headers = headers)
if str(r.status_code)[0] == "4":
print("未下载成功:", urls[num])
continue
with open(name, 'wb') as fd:
for chunk in r.iter_content():
fd.write(chunk)
except:
print "图片下载错误"
continue
#发送图片
try:
self.send_img_msg_by_uid(name, msg['user']['id'])
self.send_msg_by_uid(u'原图链接', msg['user']['id'])
self.send_msg_by_uid(sourceurls[num], msg['user']['id'])
break
except:
self.send_msg_by_uid(u'并没有搜到啥', msg['user']['id'])
continue
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
r = random.Random()
for i in range(randomlength):
str+=chars[r.randint(0, length)]
return str
def main():
bot = MyWXBot()
bot.DEBUG = True
bot.SCHEDULE_INTV = 20
bot.conf['qr'] = 'tty'
bot.run()
if __name__ == '__main__':
main()