Python爬虫(三)-网页解析(2021/4/15更新)

Python爬虫入门目录

2021/4/15更新:最后一行代码class_="post-views-count"少了一个=,已补。

所需库

from bs4 import BeautifulSoup

项目代码示例

html = askUrl("http://mwhls.top")               # 获取页面html文本
soup = BeautifulSoup(html, "html.parser")       # 使用html解析来处理html变量(变量名)
item1 = soup.find_all("article"):               # 匹配article标签
item1 = str(item)                               # 转换为字符串
item2 = soup.find_all("span", class_="post-views-count")     # 匹配span标签,且class为post-views-count。
item2 = str(item)

函数用法

先需要用上篇文章的askUrl函数来获取html文本,也可以使用文件打开,目的是获得HTML文本。

使用BeautifulSoup(a, b)函数对html文本解析,其中,a是待解析的数据,b是解析器,对于本示例来说,需要解析html变量,以html解析器。将结果赋予一个变量soup后:

soup = BeautifulSoup(html, "html.parser")

之后,使用soup.find_all()函数匹配标签。
例如,想匹配一个标签<a><a/>,使用 item = soup.find_all("a")
想只匹配前三个<a><a/>标签,使用 item = soup.find_all("a", limit=3)
而想要匹配一个class="post-views-count",使用 item = soup.find_all(class_="post-views-count") 注意class有下划线_
想要匹配一个id=main,使用item = soup.find_all(id="main")

在本项目中,要匹配mwhls.top首页中的文章,查看网页源代码(谷歌游览器使用F12)后发现十篇文章分别对应十个article标签,因此,直接匹配这个标签:

item = soup.find_all("article")

此时直接打印这个变量item,可以看到十个article标签已经成为列表存储在item中了,此时只需要用for循环遍历,就能将item中的每个文章取出,转换成字符串后就可以进行之后的正则表达式匹配,来匹配目标数据了。

此外,首页并没有显示阅读数,为了将阅读数也纳入数据库,应该对每篇文章的连接再次进行爬取,爬取的流程与首页爬取文章一样,只是匹配的东西变成了

item = soup.find_all("span", class_="post-views-count")

这串代码的意思是匹配span标签,且class=“post-views-count”,但实际使用中只需要匹配class即可,因为这个class是独一无二的。

版权声明:
作者:MWHLS
链接:http://panwj.top/465.html
来源:无镣之涯
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>