使用beautifulSoup
文章目录
- 使用beautifulSoup
- 获取属性
- 获取内容
- 嵌套选择
- 兄弟节点
- 方法选择器
- find_all
- attrs
- find
使用beautifulSoup
beautifulSoup是python的一个lxml和html的一个解析库,用于从网页中提取数据
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())
print(soup.title.string)
声明变量是html,但是这并不是一个完整的html字符串,有的节点没有闭合。
调用 prettify() 方法。这个方法可以把要解析的字符串以标准的缩进格式输出。
这里需要注意的是,输出结果里面包含 body 和 html 节点,也就是说对于不标准的 HTML 字符串 BeautifulSoup,可以自动更正格式。这一步不是由 prettify() 方法做的,而是在初始化 BeautifulSoup 时就完成了。
然后调用 soup.title.string,这实际上是输出 HTML 中 title 节点的文本内容。所以,soup.title 可以选出 HTML 中的 title 节点,再调用 string 属性就可以得到里面的文本了
##节点选择
直接调用节点的名称就可以选择节点元素,再调用 string 属性就可以得到节点内的文本了,这种选择方式速度非常快。如果单个节点结构层次非常清晰,可以选用这种方式来解析。
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')print(soup.title)
print(type(soup.title))
print(soup.title.string)
print(soup.head)
print(soup.p)
比如 string 属性,调用该属性,可以得到节点的文本内容,所以接下来的输出结果正是节点的文本内容。
最后,选择了 p 节点。不过这次情况比较特殊,我们发现结果是第一个 p 节点的内容,后面的几个 p 节点并没有选到。也就是说,当有多个节点时,这种选择方式只会选择到第一个匹配的节点,其他的后面节点都会忽略。
获取属性
每个节点可能有多个属性,比如 id 和 class 等,选择这个节点元素后,可以调用 attrs 获取所有属性:
print(soup.p.attrs)
print(soup.p.attrs['name'])
结果:
{'class': ['title'], 'name': 'dromouse'}
dromouse
其实还可以不用attrs,直接在节点后面加中括号,传入属性名就可以获得属性值
print(soup.p['name'])
print(soup.p['class'])
获取内容
可以利用 string 属性获取节点元素包含的文本内容,比如要获取第一个 p 节点的文本:
print(soup.p.string)
运行结果如下:
The Dormouse's story
再次注意一下,这里选择到的 p 节点是第一个 p 节点,获取的文本也是第一个 p 节点里面的文本。
嵌套选择
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.head.title)
print(type(soup.head.title))
print(soup.head.title.string)
运行结果如下:
<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
The Dormouse's story
第一行结果是调用 head 之后再次调用 title 而选择的 title 节点元素。然后打印输出了它的类型,可以看到,它仍然是 bs4.element.Tag 类型。也就是说,我们在 Tag 类型的基础上再次选择得到的依然还是 Tag 类型,每次返回的结果都相同,所以这样就可以做嵌套选择了。
最后,输出它的 string 属性,也就是节点里的文本内容。
###子节点和子孙节点
选取节点元素之后,如果想要获取它的直接子节点,可以调用 contents 属性
同样,我们可以调用 children 属性得到相应的结果:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.p.children)
for i, child in enumerate(soup.p.children):print(i, child)
- 如果要得到所有的子孙节点的话,可以调用 descendants 属性:
###父节点和祖先节点
如果要获取某个节点元素的父节点,可以调用 parent 属性:
因为父节点中包含子节点,输出的父节点中将和子节点一起输出。
兄弟节点
其中 next_sibling 和 previous_sibling 分别获取节点的下一个和上一个兄弟元素,next_siblings 和 previous_siblings 则分别返回后面和前面的兄弟节点。
方法选择器
前面所讲的选择方法都是通过属性来选择的,这种方法非常快,但是如果进行比较复杂的选择的话,它就比较烦琐,不够灵活了
find_all
find_all,顾名思义,就是查询所有符合条件的元素,可以给它传入一些属性或文本来得到符合条件的元素,功能十分强大。我们可以通过节点来查询元素
html='''
<div class="panel"><div class="panel-heading"><h4>Hello</h4></div><div class="panel-body"><ul class="list" id="list-1"><li class="element">Foo</li><li class="element">Bar</li><li class="element">Jay</li></ul><ul class="list list-small" id="list-2"><li class="element">Foo</li><li class="element">Bar</li></ul></div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all(name='ul'))
print(type(soup.find_all(name='ul')[0]))
[<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>, <ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>]
<class 'bs4.element.Tag'>
这里我们调用了 find_all 方法,传入 name 参数,其参数值为 ul。也就是说,我们想要查询所有 ul 节点,返回结果是列表类型,长度为 2
attrs
除了根据节点名查询,我们也可以传入一些属性来进行查询
html='''
<div class="panel"><div class="panel-heading"><h4>Hello</h4></div><div class="panel-body"><ul class="list" id="list-1" name="elements"><li class="element">Foo</li><li class="element">Bar</li><li class="element">Jay</li></ul><ul class="list list-small" id="list-2"><li class="element">Foo</li><li class="element">Bar</li></ul></div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all(attrs={'id': 'list-1'}))
print(soup.find_all(attrs={'name': 'elements'}))
运行结果:
[<ul class="list" id="list-1" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>]
[<ul class="list" id="list-1" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>]
这里查询的时候传入的是 attrs
####text
text 参数可用来匹配节点的文本,传入的形式可以是字符串,可以是正则表达式对象,示例如下:
import re
html='''
<div class="panel"><div class="panel-body"><a>Hello, this is a link</a><a>Hello, this is a link, too</a></div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all(text=re.compile('link')))
运行结果:
['Hello, this is a link', 'Hello, this is a link, too']
这里有两个 a 节点,其内部包含文本信息。这里在 find_all() 方法中传入 text 参数,该参数为正则表达式对象,结果返回所有匹配正则表达式的节点文本组成的列表。
find
除了 find_all 方法,还有 find 方法,只不过 find 方法返回的是单个元素,也就是第一个匹配的元素,而 find_all 返回的是所有匹配的元素组成的列表。
使用beautifulSoup相关推荐
- python beautifulsoup模拟点击_Python爬虫丨BeautifulSoup实践
项目分析 爬取的网站是下厨房,目标是固定栏目[本周最受欢迎] 可以看到我们要爬取的/explore/不在禁止爬取的列表内 1.先看下页面 计划拿到的信息是:菜名.所需材料.和菜名所对应的详情页URL ...
- python html解析查找字符串_用python的BeautifulSoup分析html
序言 之前用python爬取网页的时候,一直用的是regex或者自带的库sgmllib里的SGMLParser.但是遇到复杂一点的情况时,SGMLParser往往就不那么给力了!(哈,难道说我 too ...
- Windows下Python 3.6 安装BeautifulSoup库
" 介绍Python库BeautifulSoup安装." 01 - BeautifulSoup库介绍 Beautiful Soup是Python的一个库,支持Python 2和Py ...
- beautifulsoup以及正则表达式re之间的一些知识!
代码: import requests import re from bs4 import BeautifulSoup r = requests.get("https://python123 ...
- beautifulsoup里面的find()和findall()小代码测试
区别: 大白话说,就是find()可以应对于单个.然而find_all()却要一次查找好多! 代码: import requests from bs4 import BeautifulSoup r = ...
- beautifulsoup关于标签的初学习
代码: import requests from bs4 import BeautifulSoup r = requests.get("https://python123.io/ws/dem ...
- BeautifulSoup的初使用!
简单使用: python小例子链接: https://python123.io/ws/demo.html 代码: import requests from bs4 import BeautifulSo ...
- python功能性爬虫案例_Python使用requests及BeautifulSoup构建爬虫实例代码
本文研究的主要是Python使用requests及BeautifulSoup构建一个网络爬虫,具体步骤如下. 功能说明 在Python下面可使用requests模块请求某个url获取响应的html文件 ...
- 爬虫书籍-Python网络爬虫权威指南OCR库 NLTK 数据清洗 BeautifulSoup Lambda表达式 Scrapy 马尔可夫模型
Python网络爬虫权威指南 编辑推荐 适读人群 :需要抓取Web 数据的相关软件开发人员和研究人员 作为一种采集和理解网络上海量信息的方式,网页抓取技术变得越来越重要.而编写简单的自动化程序(网络爬 ...
- from beautifulsoup4 import BeautifulSoup 报错
>>> from beautifulsoup4 import BeautifulSoup Traceback (most recent call last): File &quo ...
最新文章
- 字符设备驱动程序之异步通知
- 深度优先搜索找迷宫的出路
- MySQL锁机制(myisam表所与innoDB锁)
- ios关于相机访问权限设置
- Linux 下搭建Apache,Linux 下搭建Apache 服务器
- VHDL中的分辨函数
- java中GET方式提交和POST方式提交
- 5938. 找出数组排序后的目标下标
- php umount强制,php foreach 參數強制類型轉換的問題 | 學步園
- 图解 Python 算法
- 计算机黑屏策略,小黑w7系统诊断策略服务已被禁用的还原教程
- Sting中方法举例
- selinux 导致ftp文件夹出错~
- 16. GD32F103C8T6入门教程-adc 使用教程2-dma+连续扫描方式采集数据
- 10-2 使用Channel等待任务结束
- vue项目中使用lib-flexible解决移动端适配
- order by case when then end
- vue导出excel并修改样式
- 怎样在VMWare虚拟机中的Windows系统使用U盘启动盘进入PE环境
- 解决 jq ui 弹框 select2 input 失效问题