我们已经抓取了一个HTML页面,接下来,我们使用BeautifulSoup来分析页面。
importrequestsfrom bs4 importBeautifulSoup
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())
输出
A simple example pageHereis some simple content forthis page.
html文档解析后,文档中的html元素构成一个树形结构。可以使用BeautifulSoup对象上的children属性(类型是list_iterator),访问页面的顶层元素。
list(soup.children)
输出
['html', '\n',
A simple example pageHereis some simple content forthis page.
, '\n']
可以看到,页面顶层有2个元素:
初始标签
标签
列表中还有2个换行符(\n)。可以看一下列表中元素的类型是什么:
[type(item) for item in list(soup.children)]
输出
[, , , ]
如上所示,所有对象都是BeautifulSoup中的对象:
bs4.element.Doctype – Doctype对象,包含关于文档类型的信息
bs4.element.Tag – Tag对象,表示html 标签,对象中会嵌套其他标签
bs4.element.NavigableString – 表示HTML文档中的文本,此处是指2个换行符文本的类型
Tag对象是最重要的对象类型,是我们最常打交道的对象类型。Tag对象让我们可以遍历,提取HTML文档中的标签和文本。
返回HTML文档顶层子节点的第3个节点,即标签。
html = list(soup.children)[2]
返回的节点html也是一个BeautifulSoup对象,因此可以继续访问该节点的子节点:
list(html.children)
输出
['\n',
A simple example page, '\n',
Hereis some simple content forthis page.
, '\n']
可以看到,忽略换行符,这里有2个标签,head和body。
尝试提取p标签中的文本,先找到body:
body = list(html.children)[3]
获取body标签的子标签:
list(body.children)
输出
['\n',
Hereis some simple content forthis page.
, '\n']提取p标签:
p = list(body.children)[1]
得到p标签后,就可以使用get_text方法来提取标签内的文本:
importrequestsfrom bs4 importBeautifulSoup
page=requests.get("https://kevinhwu.github.io/demo/python-scraping/simple.html")
soup=BeautifulSoup(page.content,'html.parser')#print(soup.prettify())
html = list(soup.children)[2]
body= list(html.children)[3]
p= list(body.children)[1]print(p.get_text())
输出
C:\Anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pydev\pydevconsole.py" --mode=client --port=54852
import sys; print('Python %s on %s' %(sys.version, sys.platform))
sys.path.extend(['C:\\app\\PycharmProjects', 'C:/app/PycharmProjects'])
Python3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64bit (AMD64)]
Type'copyright', 'credits' or 'license' formore information
IPython7.12.0 -- An enhanced Interactive Python. Type '?' forhelp.
PyDev console: using IPython7.12.0
Python3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64bit (AMD64)] on win32
runfile('C:/app/PycharmProjects/ArtificialIntelligence/test2.py', wdir='C:/app/PycharmProjects/ArtificialIntelligence')
Hereis some simple content for this page.