30行python代码获取微博热点并推送微信群

最近开始学习Python语言,说实话还是挺有趣的,所以周末在家捣鼓了一下python自动爬取微博热搜榜单并自动发送给微信群好友。技术主要使用了python itchat,requests,BeautifulSoup库。
以下是实现代码:

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="南大荣誉学长群" # 你真实微信中的群备注名称.
@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('发送完毕!')

使用上述代码请确保安装了pip包安装工具以及安装好import的包。如果你还不会安装,请看我的另一篇专栏有介绍如何安装pip工具!

如果要实现向好友发送消息,只需增加下面函数并调用:

def sendMsgToFriend(context):
    name = itchat.search_friends(name=u'老妈')
    a = name[0]["UserName"]
    itchat.send_msg(context,a)

完!

你可能感兴趣的:(30行python代码获取微博热点并推送微信群)