功能介绍:
微信好友发送页码,自动回复好友段子网指定网页信息,并记录相关信息。
安装相应模块:
pip install itchat
pip install requests
pip install bs4
pip install pymysql
pip install lxml
import itchat
import requests
from bs4 import BeautifulSoup
import pymysql as MySQLdb
#登录微信
itchat.auto_login(enableCmdQR='-1', hotReload=True)
def send(url, tousername, nickname):
#获取待解析页面
start_html = requests.get(url)
#指定待解析页面编码
start_html.encoding='utf-8'
#指定解析方式并解析
soup = BeautifulSoup(start_html.text, 'lxml')
#定位要获取的信息在待解析html页面的位置
list = soup.find_all(attrs={'class': 'post'})
#获取下一页链接地址,暂时无用
url = soup.find(attrs={'class': 'next'}).get('href')
#获取Mysql数据库连接
db = MySQLdb.connect("IP", "用户名", "密码", "库名")
#获取操作游标
cursor = db.cursor()
#循环解析多个相同节点
for i in list:
#获取笑话标题
title = i.find(attrs={'class': 'post-title'}).get_text()
#获取笑话内容
content = i.find(attrs={'class': 'post-content'}).get_text()
#插入数据SQL
sql='INSERT INTO python_joke(nickname,title,content) VALUES (\'' + nickname + '\',\'' + title + '\',\'' + content + '\')'
#执行插入数据SQL
cursor.execute(sql)
#提交事务
db.commit()
#将笑话内容发送给指定人
itchat.send(title + content, toUserName=tousername)
#关闭操作游标
cursor.close()
#关闭数据库连接
db.close()
#要获取好友发送的文本信息的注释
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
#获取好友发送的文本信息,并转成字符串类型
y = str(msg['Text'])
#获取发送消息的好友用户
tousername = msg.fromUserName
#获取发送消息的好友昵称
nickname = msg.User.NickName
#如果是数字,即页码
if y.isdigit():
#段子网地址
url = 'https://duanziwang.com/page/{}/'
#拼接地址
url = url.format(y)
#调用爬取方法及发送好友方法
send(str(url), tousername, nickname)
#运行
itchat.run()