前言:
假设有这样一种情况,爬虫在家中的电脑上运行,人在外面。如果我们想随时了解爬虫运行的状态,那我们需要在爬虫和手机之间实现通信。如何实现,这里介绍一个python的第三方库itchat。itchat是一个开源的微信个人号接口,可以模拟微信的网页登录,而且操作非常简单。
一、基本思路:
用itchat在PC端模拟微信网页登录,然后可以定时的,或者在异常出现的时候将爬虫状态信息通过微信发给手机端的自己。或者也可以在收到指定消息的时候做出相应回复。
二、itchat介绍:
安装:直接 pip install itchat
发消息:
import itchat
itchat.auto_login() #登录,会弹出一个二维码,手机扫码登录
itchat.send(msg='Hello',toUserName=username) #给某人发消息’Hello‘,如果去掉后面的toUserName则表示给自己发消息
#上面的username不是用户的昵称或备注,而是一串id代码,需要通过查找,再获取
friend = find_friend('小明') #查找昵称小明的用户
username = friend['UserName'] #获得小明的username
itchat.send(msg='Hello',toUserName=username) #给小明发消息
itchat.logout() #退出登录
回复消息:
import itchat
@itchat.msg_register(itchat.content.TEXT) #如果接收到文本信息,则运行下面定义的函数
def auto_reply(msg): #msg 即收到的消息体
print(msg.text) #打印收到的消息文本
return '收到消息' #回复‘收到消息’
itchat.auto_login() #登录
itchat.run() #开启自动回复,程序运行到这里会保持等待
三、举个例子:
如果我们希望爬虫运行遇到异常时,把异常发送到手机端 。
import itchat
if __name__=='__main__':
itchat.auto_login()
try: #运行爬虫
spider()
except Exception as e: #出现异常
itchat.send(e) #发送异常
如有错误,望指正。
更多itchat详细内容可以查看itchat文档
欢迎关注本人公众号,更多爬虫案例持续更新中!