Python获取微博热搜的方法

微博热搜的爬取需要用到lxml和requests两个库

url=https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6

1.分析网页的源代码:右键–查看网页源代码,从网页代码中可以获取到信息有:

(1)热搜的名字都在的子节点里

(2)热搜的排名都在的里(注意置顶微博是没有排名的!)

(3)热搜的访问量都在的子节点里

2.requests获取网页

(1)先设置url地址,然后模拟浏览器(这一步可以不用)防止被认出是爬虫程序。

###网址

url=“https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6”

###模拟浏览器,这个请求头windows下都能用

header={‘User-Agent’:‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36’}

(2)利用requests库的get()和lxml的etree()来获取网页代码

###获取html页面

html=etree.HTML(requests.get(url,headers=header).text)

3.构造xpath路径

上面第一步中三个xath路径分别是:

affair=html.xpath(’//td[@class=“td-02”]/a/text()’)

rank=html.xpath(’//td[@class=“td-01 ranktop”]/text()’)

view=html.xpath(’//td[@class=“td-02”]/span/text()’)

xpath的返回结果是列表,所以affair、rank、view都是字符串列表

4.格式化输出

需要注意的是affair中多了一个置顶热搜,我们先将他分离出来。

top=affair[0]

affair=affair[1:]

这里利用了python的切片。

print(’{0:<10}\t{1:<40}’.format(“top”,top))

for i in range(0, len(affair)):

print("{0:<10}\t{1:{3}<30}\t{2:{3}>20}".format(rank[i],affair[i],view[i],chr(12288)))

5.全部代码

###导入模块

import requests

from lxml import etree

###网址

url=“https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6”

###模拟浏览器

header={‘User-Agent’:‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36’}

###主函数

def main():

###获取html页面

html=etree.HTML(requests.get(url,headers=header).text)

rank=html.xpath(’//td[@class=“td-01 ranktop”]/text()’)

affair=html.xpath(’//td[@class=“td-02”]/a/text()’)

view = html.xpath(’//td[@class=“td-02”]/span/text()’)

top=affair[0]

affair=affair[1:]

print(’{0:<10}\t{1:<40}’.format(“top”,top))

for i in range(0, len(affair)):

print("{0:<10}\t{1:{3}<30}\t{2:{3}>20}".format(rank[i],affair[i],view[i],chr(12288)))

main()

猜你喜欢

转载自blog.csdn.net/tianqiIP/article/details/114132042
今日推荐