我们已经抓取了一个HTML页面,接下来,我们使用BeautifulSoup来分析页面。
import requests
from bs4 import BeautifulSoup
page = requests.get("https://kevinhwu.github.io/demo/python-scraping/simple.html")
soup = BeautifulSoup(page.content, 'html.parser')
导入BeautifulSoup库,创建页面解析对象soup
。
前面打印出的html页面格式很乱,如果想打印出美化格式的html页面,可以使用BeautifulSoup
对象上的prettify
方法:
print(soup.prettify())
<!DOCTYPE html>
<html>
<head>
<title>
A simple example page
</title>
</head>
<body>
<p>
Here is some simple content for this page.
</p>
</body>
</html>
html文档解析后,文档中的html元素构成一个树形结构。可以使用BeautifulSoup
对象上的children
属性(类型是list_iterator),访问页面的顶层元素。
list(soup.children)
['html', '\n', <html>
<head>
<title>
A simple example page
</title>
</head>
<body>
<p>
Here is some simple content for this page.
</p>
</body>
</html>, '\n']
可以看到,页面顶层有2个元素:
<!DOCTYPE html>
初始标签<html>
标签
列表中还有2个换行符(\n
)。可以看一下列表中元素的类型是什么:
[type(item) for item in list(soup.children)]
[<class 'bs4.element.Doctype'>, <class 'bs4.element.NavigableString'>, <class 'bs4.element.Tag'>, <class 'bs4.element.NavigableString'>]
如上所示,所有对象都是BeautifulSoup
中的对象:
bs4.element.Doctype
– Doctype对象,包含关于文档类型的信息bs4.element.Tag
– Tag对象,表示html 标签,对象中会嵌套其他标签bs4.element.NavigableString
– 表示HTML文档中的文本,此处是指2个换行符文本的类型
Tag对象是最重要的对象类型,是我们最常打交道的对象类型。Tag对象让我们可以遍历,提取HTML文档中的标签和文本。
返回HTML文档顶层子节点的第3个节点,即<html>
标签。
html = list(soup.children)[2]
返回的节点html
也是一个BeautifulSoup
对象,因此可以继续访问该节点的子节点:
list(html.children)
['\n', <head>
<title>
A simple example page
</title>
</head>, '\n', <body>
<p>
Here is some simple content for this page.
</p>
</body>, '\n']
可以看到,忽略换行符,这里有2个标签,head
和body
。
尝试提取p
标签中的文本,先找到body
:
body = list(html.children)[3]
获取body
标签的子标签:
list(body.children)
['\n', <p>
Here is some simple content for this page.
</p>, '\n']
提取p
标签:
p = list(body.children)[1]
得到p
标签后,就可以使用get_text
方法来提取标签内的文本:
p.get_text()
'\nHere is some simple content for this page.\n'