首页 > 技术文章 > 使用BeautifulSoup高效解析网页,再也不用担心睡不着觉了

feng-zhi 2021-04-23 19:33 原文

BeautifulSoup是一个可以从 HTML 或 XML 文件中提取数据的 Python 库

那需要怎么使用呢?
首先我们要安装一下这个库
1.pip install beautifulsoup4

2.pip install lxml

随便来一段html代码

html_doc = """
<html><head><title>学习python的正确姿势</title></head>
<body>
<p class="title"><b>我要学爬虫</b></p>

<p class="story">有一天,小邓想找工作实习单位了,不知道怎么选
<a href="http://example.com/1" class="sister" id="link1">一个钱多职位低</a>,
<a href="http://example.com/2" class="sister" id="link2">一个钱少职位高</a> ,
他问我,我到底选钱多还是钱少的?</p>

<p class="story">...</p>

"""

接着将 html 的源代码传给 BeautifulSoup
soup=BeautifulSoup(html_doc,"lxml")

然后就不需要写正则匹配了

以下为方法以及实例

#获得标签内的文本
# 学习python的正确姿势
#
# 我要学爬虫
# 有一天,小邓想找工作实习单位了,不知道怎么选
# 一个钱多职位低,
# 一个钱少职位高 ,
# 他问我,我到底选钱多还是钱少的?
# ...
print(soup.text)

# 获取标题的内容
# 学习python的正确姿势
print(soup.title.string)

# 获取 title 的父级标签
# head
print(soup.title.parent.name)

# 获取超链接
# <a class="sister" href="http://example.com/1" id="link1">一个钱多职位低</a>
print(soup.a)

# 获取所有超链接
# [<a class="sister" href="http://example.com/1" id="link1">一个钱多职位低</a>, <a class="sister" href="http://example.com/2" id="link2">一个钱少职位高</a>]
print(soup.find_all('a'))

# 获取 id 为 link2 的超链接
# <a class="sister" href="http://example.com/2" id="link2">一个钱少职位高</a>
print(soup.find(id="link2"))

除了find方法之外,如果你对css比较熟悉也可以使用 select 方法

soup = BeautifulSoup(html_doc,'lxml')

print(soup.select("title"))
print(soup.select("body a"))
print(soup.select("p > #link1"))

以上就是 BeautifulSoup 常用的方法
进一步了解可去
BeautifulSoup文档

有了它,妈妈再也不用担心我的正则表达式了,下次还有人这样问你
年轻人,不会正则表达式你睡得着觉?有点出息没有?
你可以傲娇的告诉他

我可以睡个安稳觉咧!
爬虫的教程都是我找网上大佬学的

本篇章到此结束!

推荐阅读