用 Python 监控知乎和微博的热门话题( 二 )

这里我利用了 script 中热榜数据的列表结构 , 在定位取出相关字符串后 , 先将 js 中的 true 和 false 转化为 Python 中的 True 和 False , 最后直接通过 eval() 来将字符串转化为直接可用的数据列表 。
运行代码结果如图:

用 Python 监控知乎和微博的热门话题

文章插图
 
至于对微博热门的解析 , 就是中规中矩地利用 BeautifulSoup 来对网页元素进行定位获取:
import requestsfrom bs4 import BeautifulSoup
url = "https://s.weibo.com/top/summary"headers={"User-Agent":"","Cookie":""}wb_response = requests.get(url,headers=headers)webcontent = wb_response.textsoup = BeautifulSoup(webcontent,"html.parser")index_list = soup.find_all("td",class_="td-01")title_list = soup.find_all("td",class_="td-02")level_list = soup.find_all("td",class_="td-03") topic_list = []for i in range(len(index_list)): item_index = index_list[i].get_text(strip = True) if item_index=="": item_index = "0" item_title = title_list[i].a.get_text(strip = True) if title_list[i].span: item_mark = title_list[i].span.get_text(strip = True) else: item_mark = "置顶" item_level = level_list[i].get_text(strip = True) topic_list.Append({"index":item_index,"title":item_title,"mark":item_mark,"level":item_level,"link":f"https://s.weibo.com/weibo?q=%23{item_title}%23&Refer=top"})print(topic_list)
通过解析 , 将微博热门数据逐条存入列表中:
用 Python 监控知乎和微博的热门话题

文章插图
 
后续对拿到的数据加以处理展示 , 即可得到很多有趣的应用或实现某些功能 。例如集成诸多平台排行榜的 “今日热榜”:
用 Python 监控知乎和微博的热门话题

文章插图
 
?????今日热榜链接:https://tophub.today因为并未展开爬虫细节 , 今天的总结也比较简单:
  1. 首先在选取要爬的网址时要给自己降低难度 , 例如同样是知乎热榜 , zhihu.com/hot 需要登陆 , 而 zhihu.com/billboard 无需登录便可访问
  2. 解析爬取到的内容时 , 要结合具体页面内容选择最便捷的方式 。当需要批量爬取相似页面时 , 也要尽量整理通用的解析策略 。
代码已上传 GitHub , 链接如下:https://github.com/pengfexue2/hot_display.git当然 , 拿到数据只是开始 , 后续如何去处理才是关键和价值所在 , 之后我们继续探讨 。




推荐阅读