爬取新浪微博热搜排行
作者:互联网
爬取新浪微博热搜排行
1.1 爬虫基本原理解析
- 什么是爬虫
- 通过编写程序模拟浏览器上网 在互联网抓取数据的过程
- 分类
- 通用爬虫
- 搜索引擎用的爬虫系统
- 尽可能把互联网的所有网页下载 放到本地服务器形成备份 在对这些网页做相关处理 (提取关键字 去掉广告) 每隔一段时间重新获取
- 举例
- 百度搜索博为峰 --百度快照–访问的是百度服务器的缓存数据 –
- 好处 – 如果网页被封掉了 百度快照 – 服务器 有可能会有备份(不能爬图片 只能是文本 /文字相关的 )
- 聚焦爬虫
- 爬虫程序员写的针对某种内容爬虫 面向需求
- (这节课的新浪微博就是聚焦爬虫)
- 通用爬虫
- 爬虫价值
- 获取数据
- 对于软件测试来讲
- 获取有效数据 为测试提供便捷 (排行–获取数据–和数据库数据进行对比 )
- 提高编程技能
- 如何爬虫
- 模拟浏览器发送请求
- 对数据进行解析
1.2 网页源码获取及转换
-
环境配置 类库安装
- python
- pip install requests
-
对获取数据进行解析
-
etree
-
pip install lxml
-
lxml
- 是一个python 的第三方模块 主要功能是如何解析和提取 HTML/xml
- 可以结合xpath语法 进行快速定位特定元素以及节点信息
-
请求技术点
- 如何发送请求
- 获取响应数据(文本)
- 伪造请求头
- 将响应文本信息转化成xpath结构
from lxml import etree import requests # 伪装请求头 headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"} res = requests.get("https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6",headers=headers) # 获取响应状态码 print(res.status_code) # 获取响应文本信息 print(res.text) print(type(res.text)) # 查看请求头信息 print(res.request.headers) html = etree.HTML(res.text) print(type(html))
-
1.3 节点、属性、内容的获取
-
标签构成
- 标签名 属性 属性值
-
提取响应title
-
通过路径
-
html.xpath("/html/head/title/text()" – 绝对路径
-
//title/text() – 相对路径提取
-
//a.text() – 获取当前网页 所有a标签的文本信息 – 以列表方式进行返回
-
获取标签详情
-
from lxml.html import tostring result = html.xpath("//title")[0] print('看结果这里', tostring(result, encoding="utf-8").decode("utf-8"))
-
-
-
指定标签属性值获取
-
//a – 获取绝对路径的标签
-
根据标签属性值获取指定标签
-
//a[@class='cur']/text()
-
通过多个属性定位标签
-
html.xpath("//a[@class='cur' and @title='热搜榜']/text()")
-
-
-
-
1.4 爬取新浪微博热搜思路梳理
-
获取请求url
-
https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6
-
-
建立请求 并将响应数据解析成html接口
-
解析网页 提取 热搜排行 热搜内容 热搜数
-
将获取信息进行处理 信息一一对
- python 列表获取数据
- for 循环
from lxml import etree
import requests
from lxml.html import tostring
res = requests.get("https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6")
# 数据解析 -- 把网页变成xpath 结构
html = etree.HTML(res.text)
# 排行
top = html.xpath('//td[@class="td-01 ranktop"]/text()')
# 热搜内容
content = html.xpath('//td[@class="td-02"]/a/text()')
# 热搜数
hot = html.xpath('//td[@class="td-02"]/span/text()')
# print(top)
# print(content)
# print(hot)
print(len(top), len(content), len(hot))
# 内容多一条 -- (热搜置顶)
for i in range(len(hot)):
print(top[i], content[i + 1], hot[i])
标签:xpath,text,top,爬虫,爬取,print,html,排行,微博热 来源: https://blog.csdn.net/weixin_46984154/article/details/112777367