本帖最后由 内裤超人 于 2019-6-18 15:43 编辑
自己写来玩的,没什么技术
[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*
#!/usr/bin/env python
import re
import json
import os
import logging
import time
import itchat
import requests
from urllib import parse
from bs4 import BeautifulSoup
logging.basicConfig(level=logging.INFO, format='\n%(asctime)s - %(levelname)s: %(message)s')
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36',
'Connection': 'keep-alive',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Referer': 'https://www.baidu.com/',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8'
}
URL = "https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=&st=-1&fm=result&fr=&sf=1&fmq=1560827301042_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&ctd=1560827301044%5E00_1902X431&sid=&word="
'''
获取好友信息
'''
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
if '图片@' in msg['Text']:
itchat.send('正在获取相关图片中...,请稍等!',toUserName=msg['FromUserName'])
text = msg['Text'][msg['Text'].find('@') + 1:]
get_img_url(text)
send_img_data = read_img(make_dir())
if len(send_img_data) > 0:
for i in range(0,5):
res = itchat.send_image(send_img_data[i],toUserName=msg['FromUserName'])
if res['BaseResponse']['Ret'] == 1205:
return '获取过于频繁'
else:
return '获取'+msg['Text']+'成功'
else:
return "暂无"+msg['Text']+"相关图片"
else:
return '获取图片请发送 图片@搞笑,@后面为获取相关图片的描述'
'''
获取表情包图片路径
'''
def get_img_url(text):
url = URL+parse.quote(text)
rep = requests.get(url,headers=headers).text
soup = BeautifulSoup(rep,'lxml')
data = soup.select('li.imgitem > div.imgbox > a > img')
url_list = []
for url in data:
img_url = url.get('data-imgurl')
if re.search(r"\.(jpg|png)$",img_url):
url_list.append(img_url)
download_img(url_list)
'''
下载文件
'''
def download_img(links):
for link in links:
img = requests.get(link,headers=headers)
real_img = img.content
with open(make_dir()+str(round(time.time() * 1000))+'.jpg', "wb") as img:
img.write(real_img)
logging.info('正在下载文件:'+link)
logging.info('下载完成')
'''
读取文件夹内容
'''
def read_img(path):
files = os.listdir(path)
img_name = []
for file in files:
if not os.path.isdir(file):
file_time = int(file[:-4])
now_time = round(time.time() * 1000)
if now_time - file_time < 15000:
img_name.append(path+file)
return img_name
'''
创建文件夹
'''
def make_dir():
path = "F:/www/Python/image/"
isexists = os.path.exists(path)
if not isexists:
os.makedirs(path)
else:
pass
return path
itchat.auto_login()
itchat.run()
|