最近開始學(xué)習(xí)Python語言谴蔑,說實(shí)話還是挺有趣的,所以周末在家搗鼓了一下python自動(dòng)爬取微博熱搜榜單并自動(dòng)發(fā)送給微信群好友龟梦。技術(shù)主要使用了python itchat,requests,BeautifulSoup庫。
以下是實(shí)現(xiàn)代碼:
import itchat
from itchat.content import TEXT
from itchat.content import *
import requests
from bs4 import BeautifulSoup
r=requests.get('https://s.weibo.com/top/summary?cate=realtimehot')
str1='今日微博熱搜消息\n'
if(r.status_code==200):
r.encoding='utf-8'
bs=BeautifulSoup(r.text,features="lxml")
rank=bs.select('.td-02 a')
for index in range(10):
str1+=str(index+1)+'.'+rank[index].text.strip()+'https://s.weibo.com'+rank[index]['href']+'\n'
itchat.auto_login(hotReload=True)
itchat.send(u'Hello,world','filehelper')
groupName="南大榮譽(yù)學(xué)長群" # 你真實(shí)微信中的群備注名稱.
@itchat.msg_register(TEXT, isGroupChat=True)
def SentChatRoomsMsg(name, context):
itchat.get_chatrooms(update=True)
iRoom = itchat.search_chatrooms(name)
for room in iRoom:
if room['NickName'] == name:
userName = room['UserName']
break
itchat.send_msg(context, userName)
SentChatRoomsMsg(groupName,str1)
print('發(fā)送完畢窃躲!')
使用上述代碼請(qǐng)確保安裝了pip包安裝工具以及安裝好import的包计贰。如果你還不會(huì)安裝,請(qǐng)看我的另一篇專欄有介紹如何安裝pip工具蒂窒!
如果要實(shí)現(xiàn)向好友發(fā)送消息躁倒,只需增加下面函數(shù)并調(diào)用:
def sendMsgToFriend(context):
name = itchat.search_friends(name=u'老媽')
a = name[0]["UserName"]
itchat.send_msg(context,a)
完!