BeatifulSoup
BeatifulSoup
(1)介绍
Beautiful Soup是Python库,用于解析HTML和XML文档。它提供简单而强大的工具,帮助用户从网页中提取数据。通过查找元素、遍历文档树和处理编码问题,它简化了数据提取过程。适用于网页抓取、数据挖掘和分析等应用场景。
pip install beautifulsoup4
from bs4 import BeautifulSoup
(2)解析器
- 内置解析器
html.parser
soup = BeautifulSoup('页面源码',html.parser)
- 第三方解析器
lxml
soup = BeautifulSoup('页面源码','lxml')
- html5lib
pip install html5lib
soup = BeautifulSoup('页面源码','html5lib')
(3)使用
(1)生成soup对象
- 打开本地文件
soup = BeautifulSoup(open('index.html'),'lxml')
- 直接把页面源码放进去
soup = BeautifulSoup('<html>data</html>','lxml')
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
url = 'http://www.baidu.com'
headers = {
'User-Agent': UserAgent().random
}
res = requests.get(url=url,headers=headers)
soup = BeautifulSoup(res.text,'lxml')
print(soup)
(4)BeautifulSoup四个对象
(1)BeautifulSoup对象
- 代表整个解析后的HTML文档,是最顶层的对象。
- 它包含了整个文档的全部内容,并提供了操作HTML文档的方法和属性。
soup = BeautifulSoup(res.text, 'lxml')
(2)Tag对象
- 表示HTML中的标签,如
<p>、<a>等。 - Tag对象包含了标签的名称和对应的属性,并可以通过Tag对象来获取标签内的内容或进行进一步的操作。
- 可以通过传递HTML文档给BeautifulSoup类初始化的方式创建Tag对象。
(1)查找tag对象
- 通过
soup.tag名获取到指定标签对象
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""
soup = BeautifulSoup(html_doc, 'lxml')
print(soup.head, type(soup.head))
# <head><title>The Dormouse's story</title></head> <class 'bs4.element.Tag'>
print(soup.title, type(soup.title))
# <title>The Dormouse's story</title> <class 'bs4.element.Tag'>
print(soup.a, type(soup.a))
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> <class 'bs4.element.Tag'>
print(soup.p.b)
# <b>The Dormouse's story</b>
(2)查找tag对象的标签名和属性
- 通过
soup.tag名.属性名获取到指定标签属性名对应的属性值
print(soup.a.name) # a
print(soup.p.b.name) # b
print(soup.a["href"]) # http://example.com/elsie
print(soup.a.attrs) # {'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
(3)返回多值的属性
print(soup.a["class"]) # ['sister']
(4)修改tag的属性
soup.a["class"] = ["sister c1"]
# 删除第一个a标签的id属性值
del soup.a["id"]
(5)获取标签对象的文本内容
print(soup.p.string) # 直接拿文本内容
# 拿到一个生成器对象, 取到p下所有的文本内容
print(soup.p.strings)
# <generator object Tag._all_strings at 0x000001AEFAEC2FF0>
for i in soup.p.strings:
print(i)
# The Dormouse's story
总结:
三种拿文本的方式
string
text
get_text()
(5)搜索文档树语法
(1)find_all 查找所有
- 在当前页面文档中查找所有符合条件的标签
soup.find_all(name='a')
soup.find_all(name=['a', 'p'])
soup.find_all(True) # 匹配所有的tag,不会返回字符串节点
# 返回所有 href 属性等于 "http://example.com/tillie" 的标签。
print(soup.find_all(href="http://example.com/tillie"))
# 返回所有包含文本 "Elsie" 的标签
print(soup.find_all(text="Elsie"))
# 返回所有包含文本 "Tillie"、"Elsie" 或 "Lacie" 的标签。
print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
# 返回所有a标签,限制2个
print(soup.find_all("a", limit=2))
# 只会查找当前soup文档的直接子元素中的 <div> 标签。
print(soup.find_all("div", recursive=False))
(2)find 查找单个
find()方法用于在文档中查找符合条件的tag,并返回第一个匹配的结果。- 它可以通过指定name、attrs、recursive和string等参数来过滤查找结果。
(6)select语法
Beautiful Soup库中的
select()方法是用于通过 CSS 选择器来选择元素的方法。它返回匹配选择器的所有元素列表。语法:
select(css_selector)
css_selector: 要使用的CSS选择器字符串。
选择器:
- 通过标签名选择:例如,
'p'选择所有<p>标签。 - 通过类名选择:例如,
'.classname'选择所有带有指定类名的元素。 - 通过ID选择:例如,
'#idname'选择具有指定ID的元素。 - 通过属性选择:例如,
'[attribute=value]'选择具有指定属性值的元素。 - 组合选择器:可以组合多个选择器,例如,
'p.title'选择所有带有class="title"的<p>元素。
- 通过标签名选择:例如,
返回值:
select()方法返回一个列表,包含匹配选择器的所有元素。
示例:
from bs4 import BeautifulSoup # HTML文档
html_doc = """
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<div id="content">
<p class="para1">Paragraph 1</p>
<p class="para2">Paragraph 2</p>
<p class="para1">Paragraph 3</p>
</div>
</body>
</html>
""" # 创建BeautifulSoup对象
soup = BeautifulSoup(html_doc, 'html.parser') # 选择所有 <p> 标签
paragraphs = soup.select('p')
print(paragraphs) # 选择类为 "para1" 的 <p> 标签
para1 = soup.select('.para1')
print(para1) # 选择ID为 "content" 的 <div> 标签
content_div = soup.select('#content')
print(content_div)
输出:
[<p class="para1">Paragraph 1</p>, <p class="para2">Paragraph 2</p>, <p class="para1">Paragraph 3</p>]
[<p class="para1">Paragraph 1</p>, <p class="para1">Paragraph 3</p>]
[<div id="content"><p class="para1">Paragraph 1</p><p class="para2">Paragraph 2</p><p class="para1">Paragraph 3</p></div>]
BeatifulSoup的更多相关文章
- 爬虫 BeatifulSoup 模块
BeatifulSoup 模块 介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库 安装 pip install beautifulsoup4 解析器下载 ...
- 爬虫基础以及 re,BeatifulSoup,requests模块使用
爬虫基础以及BeatifulSoup模块使用 爬虫的定义:向网站发起请求,获取资源后分析并提取有用数据的程序 爬虫的流程 发送请求 ---> request 获取响应内容 ---> res ...
- linux上安装BeatifulSoup(第三方python库)
1. 什么是beatifulsoup? beatifulsoup官网http://www.crummy.com/software/BeautifulSoup/ BeatifulSoup是用Python ...
- python 简单爬虫(beatifulsoup)
---恢复内容开始--- python爬虫学习从0开始 第一次学习了python语法,迫不及待的来开始python的项目.首先接触了爬虫,是一个简单爬虫.个人感觉python非常简洁,相比起java或 ...
- 我的第一个py爬虫-小白(beatifulsoup)
一.基本上所有的python第一步都是安装.安装 我用到的第三方安装包(beatifulsoup4.re.requests).还要安装lxml 二.找个http开头的网址我找的是url="h ...
- BeatifulSoup文档地址
http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
- BeatifulSoup模块
一.介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你 ...
- 爬虫(七):BeatifulSoup模块
1. Beautiful Soup介绍 Beautiful Soup是一个可以从HTML或XML文件中提取数据的Python库.能将即将要进行解析的源码加载到bs对象,调用bs对象中相关的方法或属性进 ...
- BeatifulSoup在测试工作中的应用
近期要做一个项目,重复性劳动比较多,小伙伴建议我用Jsoup,但是由于项目紧急,我直接选择了BeautifulSoup,关键原因是我Java语言不如Python掌握的熟练啊!所以,查了一圈它的中文文档 ...
- BeautifulSoup
参考:http://www.freebuf.com/news/special/96763.html 相关资料:http://www.jb51.net/article/65287.htm 1.Pytho ...
随机推荐
- Linux centos 运行telnet命令command not found的解决方法
Linux centos 运行telnet命令,出现下面的错误提示: 1 2 [root@localhost ~]# telnet 127.0.0.1 -bash: telnet: command ...
- linux下的nginx重启命令常见以下3种:
systemctl restart nginx service nginx restart /usr/sbin/nginx -s reload
- 【Guava工具类】Strings&Ints
String相关工具 Strings Guava 提供了一系列用于字符串处理的工具: 对字符串为null或空的处理 nullToEmpty(@Nullable String string):如果非空, ...
- 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
引言 ❝ 小编是一名10年+的.NET Coder,期间也写过Java.Python,从中深刻的认识到了软件开发与语言的无关性.现在小编已经脱离了一线开发岗位,在带领团队的过程中,发现了很多的问题,究 ...
- study PostgreSQL【2-FireDAC连接PostgreSQL】
就这么个简单问题,一下午时间.想想就憋屈. 那么牛逼哄哄FireDAC居然连接PostgreSQL出问题了.帮助中说的啥意思,咱也不明白.网上一通也是云里雾里. 上干货,具体点: TFDConnect ...
- lombok用法
加入 maven 依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lo ...
- FastAPI依赖注入与上下文管理
title: FastAPI依赖注入与上下文管理 date: 2025/04/07 00:28:04 updated: 2025/04/07 00:28:04 author: cmdragon exc ...
- 《数组》--DAY1--二分查找
分治算法--二分查找(返回下标) 1.定义:在有序列表中,每次查找范围折半 列表若存在重复元素,返回下标不唯一 优点:比较次数少,速度快,性能好:缺点:要求列表有序 注意区分while(left &l ...
- 配置springmvc的springmvc.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...
- Eclipse 安装 阿里P3C编码规范插件
操作:Help -> Install New Software -> add name: p3c location:https://p3c.alibaba.com/plugin/eclip ...