Python 爬虫 – BeautifulSoup分析页面

我们已经抓取了一个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个标签,headbody

尝试提取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'


浙ICP备17015664号-1 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载