认识爬虫:beautifulsoup4 库如何使用三种方式提取 html 网页元素?

通过前面网页下载器得到一个网页源代码的很长的字符串,接下来则是要通过网页解析器对网页源代码中的信息进行提取,beautifulsoup4 库作为第三方插件同时支持 html、xml 的解析。通过将网页下载器下载的 html 字符串解析成为一个 BeautifulSoup 的对象,最后从这个对象中根据网页源代码的 html 标签、属性等因素提取我们需要的内容。

1、准备网页下载器获取的源代码
 1# 首先获取到网页下载器已经下载到的网页源代码
 2# 这里直接取官方的案例
 3html_doc = """
 4<html><head><title>The Dormouse's story</title></head>
 5<body>
 6<p class="title"><b>The Dormouse's story</b></p>
 7
 8<p class="story">Once upon a time there were three little sisters; and their names were
 9<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
10<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
11<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
12and they lived at the bottom of a well.</p>
13
14<p class="story">...</p>
15"""
2、导入 beautifulsoup4 库并创建解析对象
1# 导入 beautifulsoup4 库、用于完成解析
2from bs4 import BeautifulSoup
3
4'''
5创建 BeautifulSoup 对象、html_doc 为执行要解析的字符串、html.parser 为指定的解析器,
6除此之外,还有其他的解析库,比如 htm5llib、lxml,各个解析库各有优势
7'''
8beau_soup = BeautifulSoup(html_doc, 'html.parser')
3、使用结构化的方式获取元素、属性等
 1'''
 2获取结构化元素或属性
 3'''
 4# 获取 title 元素、也就是 title 标签
 5print beau_soup.title
 6# <title>The Dormouse's story</title>
 7
 8# 获取第一个 p 元素
 9print beau_soup.p
10# <p class="title"><b>The Dormouse's story</b></p>
11
12# 获取第一个 p 元素的 class 属性
13print beau_soup.p['class']
14# [u'title']
15
16# 获取第一个 p 元素下面的 b 元素
17print beau_soup.p.b
18# <b>The Dormouse's story</b>
19
20# 获取 p 元素的父节点的源代码
21print beau_soup.p.parent
22'''
23<body>
24<p class="title"><b>The Dormouse's story</b></p>
25<p class="story">Once upon a time there were three little sisters; and their names were
26<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
27<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
28<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
29and they lived at the bottom of a well.</p>
30<p class="story">...</p>
31</body>
32'''
33# 获取 p 元素的父节点的名称
34print beau_soup.p.parent.name
35# body
4、通过元素搜索的方式获取元素、属性等
 1'''
 2除了通过结构化的方式获取元素,在其他情况使用结构化不容易获取元素时,
 3可以使用类似于的搜索的功能对源代码的标签、属性等进行筛选。
 4find() 函数、find_all() 函数可以利用多个条件的模式对源代码标签等
 5进行搜索。
 6'''
 7'''
 8find_all(self, name=None, attrs={}, recursive=True, text=None,
 9                 limit=None, **kwargs)
10结果返回一个 list 集合
11'''
12
13# 搜索所有 p 元素、然后返回一个 p 元素的 list
14print beau_soup.find_all('p')
15# 搜索所有 a 元素、然后返回一个 a 元素的 list
16links = beau_soup.find_all('a')
17for link in links:
18    print '未爬取的链接:',link['href']
19
20# 多条件查找,获取 p 元素、并且 class 属性 == title 的元素
21print beau_soup.find_all('p',class_='title')
22'''
23 find(self, name=None, attrs={}, recursive=True, text=None,
24             **kwargs)
25结果只返回一个,如果有多个则返回第一个,相比 find_all() 函数少了 limit 参数
26'''
27
28# 通过 id 搜索
29print beau_soup.find(id='link3')
30
31# 多条件查找,获取 p 元素、并且 class 属性 == title 的元素
32print beau_soup.find('p',class_='title')
33
34import re
35
36# 多条件查找,获取 a 元素的 href 属性中包含 lacie 字符串的元素对象
37print beau_soup.find('a',href=re.compile(r"lacie"))
5、通过样式选择器的方式获取元素、属性等
1'''
2除了上述使用结构化获取、元素/属性查找的方式,还提供了 select()
3函数通过 css 样式选择器的方式进行元素获取,这个函数返回的也是一个 list
4'''
5print beau_soup.select('html head title')
6# html head title 在 css 选择器中表示 html 标签下面的 head 标签下面的 title 标签
7
8print beau_soup.select('#link3')
9# #link3 样式选择器中 id 为 link3 的元素

更多精彩前往微信公众号【Python 集中营】,关注获取《python 从入门到精通全套视频》

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
### 回答1: BeautifulSoup4 可以使用以下三种方式提取 HTML 网页元素: 1. 标签选择器:使用标签名称来选择元素。例如,使用 `soup.select('p')` 可以选择所有的 `<p>` 标签。 2. 类选择器:使用类名来选择元素。例如,使用 `soup.select('.class_name')` 可以选择所有具有 `class="class_name"` 属性的元素。 3. ID 选择器:使用 ID 名称来选择元素。例如,使用 `soup.select('#id_name')` 可以选择具有 `id="id_name"` 属性的元素。 ### 回答2: BeautifulSoup4是一款PythonHTML和XML解析器,可以帮助我们从HTML提取信息。下面将介绍三种不同方式HTML提取元素。 1. 基于标签提取 基本上Web上的所有数据是通过HTML标签来组织的,而BeautifulSoup4正是根据这些标签来提取数据的。 首先,我们需要安装BeautifulSoup解析器。安装的方法为: ``` pip install beautifulsoup4 pip install lxml # 这是一个解析器 ``` 接着,导入模块并使用如下代码读取HTML文件: ``` from bs4 import BeautifulSoup with open('example.html', 'r') as f: html = f.read() soup = BeautifulSoup(html, 'lxml') ``` 其中,example.html为我们需要提取数据的HTML网页。然后,我们可以通过以下代码找到网页中的第一个标题(h1标签): ``` print(soup.h1) ``` 如果需要在网页中查找所有的标签,可以使用find_all方法: ``` soup.find_all('a') ``` 其中第一个参数为标签名,如'a',表示查找所有的超链接。 2. 基于属性提取 有时候,我们需要找到带有特定属性的标签,例如class属性为red的div标签。可以使用find_all方法,将属性和属性值作为参数传入: ``` soup.find_all('div', {'class': 'red'}) ``` 3. 基于CSS选择器提取 我们还可以使用CSS选择器在BeautifulSoup中查找元素。例如,我们可以使用以下代码查找所有带有class为red的div标签: ``` soup.select('div.red') ``` 其中,'div.red'表示查找div标签中class属性为red的所有元素。 总之,无论使用哪一种方式BeautifulSoup都是一个十分好用的,可以让我们轻松地从HTML提取所需的信息。 ### 回答3: BeautifulSoup4是一个Python,它可以帮助我们从HTML和XML文档中提取特定的信息,以便进行数据挖掘和分析。 在使用BeautifulSoup4提取HTML网页元素时,有三种方式: 1.基于标签的解析方法 这是最常见的一种方法。它基于HTML标签来解析文档,并返回标签对象或标签列表。在这种方法中,我们使用“soup.tagName”或“soup.findAll(‘tagName’)”语句来获取所有指定标签的对象或标签列表。 例如,下面的代码将从HTML文档中提取所有段落标签,并将它们输出到控制台: from bs4 import BeautifulSoup import requests url = 'http://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') paragraphs = soup.findAll('p') for paragraph in paragraphs: print(paragraph) 2.基于属性的解析方法 这种方法是基于HTML标签的属性来解析文档,并返回标签对象或标签列表。在这种方法中,我们使用“soup.find(‘tagName’, {‘attributeName’: ‘value’})”或“soup.findAll(‘tagName’, {‘attributeName’: ‘value’})”语句来获取所有指定标签的对象或标签列表。 例如,下面的代码将从HTML文档中提取所有带有“class”属性的标签,并将它们输出到控制台: from bs4 import BeautifulSoup import requests url = 'http://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') tags = soup.findAll(class_='example') for tag in tags: print(tag) 3.基于CSS选择器的解析方法 这种方法与基于属性的方法类似,但它更灵活,并支持更复杂的选择器。在这种方法中,我们使用“soup.select(‘tagName CSSSelector’)”语句来获取所有符合选择器条件的标签对象或标签列表。 例如,下面的代码将从HTML文档中提取所有段落标签和内容为“example”的标签,并将它们输出到控制台: from bs4 import BeautifulSoup import requests url = 'http://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') tags = soup.select('p, [content="example"]') for tag in tags: print(tag) 无论使用哪种解析方法,我们都可以轻松地从HTML文档中提取所需的元素。在一个完整的项目中,这可以帮助我们自动化网站抓取、数据分析和报告生成等任务。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python 集中营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值