Python开发【模块】:BeautifulSoup
BeautifulSoup
BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单
1、安装:
pip3 install beautifulsoup4
pip install lxml # python2.x
2、简单使用:
from bs4 import BeautifulSoup html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
asdf
<div class="title">
<b>The Dormouse's story总共</b>
<h1>f</h1>
</div>
<div class="story">Once upon a time there were three little sisters; and their names were
<a class="sister0" id="link1">Els<span>f</span>ie</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.</div>
ad<br/>sf
<p class="story">...</p>
</body>
</html>
""" # soup = BeautifulSoup(html_doc, features="lxml")
soup = BeautifulSoup(html_doc, features="html.parser") # 等同于上面
# 找到第一个a标签
tag1 = soup.find(name='a')
# 找到所有的a标签
tag2 = soup.find_all(name='a')
# 找到id=link2的标签
tag3 = soup.select('#link2') print(tag1)
print(tag2)
print(tag3)
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
3、标签方法:
① name标签名称
# name
tag = soup.find('a')
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
name = tag.name # 获取
print(name) # a
tag.name = 'span' # 设置 替换第一个a标签为span标签
print(soup)
② attrs标签属性
# attrs
tag = soup.find('a')
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
attrs = tag.attrs # 获取
print(attrs)
# {'class': ['sister0'], 'id': 'link1'}
tag.attrs = {'ik':123} # 设置属性
tag.attrs['id'] = 'iiiii' # 更改id
print(soup)
③ children所有子标签
# 子标签,只是获取儿子
tag = soup.find('a')
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
v = tag.children
print(v)
# <list_iterator object at 0x02E71230>
for i in v:
print(i)
# Els
# <span>f</span>
# ie
④ descendants子子孙孙标签
# 获得子子孙孙
body = soup.find('body')
v = body.descendants
print(v)
for i in v:
print(i)
⑤ clear将标签的所有子标签全部清空(保留标签名)
# 清空表签内容
tag = soup.find('body')
tag.clear()
print(soup) # <html><head><title>The Dormouse's story</title></head>
# <body></body>
# </html>
⑥ decompose,递归的删除所有的标签
# 递归的删除所有的标签
body = soup.find('body')
body.decompose()
print(soup) # <html><head><title>The Dormouse's story</title></head>
#
# </html>
⑦ extract递归的删除所有的标签,并获取删除的标签
# 递归的删除所有的标签,并获取删除的标签
body = soup.find('body')
v = body.extract()
print(soup)
# <html><head><title>The Dormouse's story</title></head>
#
# </html>
print(v,type(v))
# <body>
# asdf
# <div class="title">
# <b>The Dormouse's story总共</b>
# <h1>f</h1>
# </div>
# <div id="story">Once upon a time there were three little sisters; and their names were
# <a class="sister0" id="link1">Els<span>f</span>ie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
# and they lived at the bottom of a well.</div>
# ad<br/>sf
# <p class="story">...</p>
# </body> <class 'bs4.element.Tag'>
⑧ decode转换为字符串(含当前标签);decode_contents(不含当前标签)
# 转换为字符串
tag = soup.find('a')
v1 = tag.decode()
print(v1)
v2 = tag.decode_contents()
print(v2) # <a class="sister0" id="link1">Els<span>f</span>ie</a>
# Els<span>f</span>ie
⑨ find获取匹配的第一个标签
# find使用
tag = soup.find('a')
print(tag)
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
tag = soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie') # recursive子子孙孙中去找
print(tag)
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
tag = soup.find(name='a', class_='sister', recursive=True, text='Lacie')
print(tag)
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
⑩ find_all获取匹配的所有标签
####### 单标签 #######
tags = soup.find_all('a')
print(tags)
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] tags = soup.find_all('a',limit=1)
print(tags)
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>] tags = soup.find_all(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')
print(tags)
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>] ####### 列表 #######
v = soup.find_all(name=['a','div']) # 获取所有的a标签和div标签,列表形式
print(v) v = soup.find_all(class_=['sister0', 'sister']) # 所有class是sister0和sister的标签
print(v)
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] v = soup.find_all(text=['Tillie']) # 获取到匹配的内容非标签
print(v, type(v[0]))
# ['Tillie'] <class 'bs4.element.NavigableString'> v = soup.find_all(id=['link1','link2']) # 获取多个id
print(v)
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>] v = soup.find_all(href=['link1','link2']) # 获取多个href
print(v)
# [] # ####### 正则 #######
import re
rep = re.compile('p')
rep = re.compile('^p')
v = soup.find_all(name=rep)
print(v) rep = re.compile('sister.*')
v = soup.find_all(class_=rep)
print(v) rep = re.compile('http://www.oldboy.com/static/.*')
v = soup.find_all(href=rep)
print(v) ####### 方法筛选 #######
def func(tag):
return tag.has_attr('class') and tag.has_attr('id')
v = soup.find_all(name=func)
print(v)
# [<a class="sister0" id="link1">Els<span>f</span>ie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] ## get,获取标签属性
tag = soup.find('a')
v = tag.get('id')
print(v)
# link1
⑪ has_attr检查标签是否具有该属性
# 标签是否具有该属性
tag = soup.find('a')
v = tag.has_attr('id')
print(v)
# True
⑫ get_text获取标签内部文本内容
# 获取标签内部文本内容
tag = soup.find('a')
# <a class="sister0" id="link1">Els<span>f</span>ie</a>
v = tag.get_text('##') # 以##进行分割
print(v)
# Els##f##ie
⑬ index检查标签在某标签中的索引位置
# 获取标签所在的索引,从0开始
tag = soup.find('body')
v = tag.index(tag.find('div'))
print(v)
# 1 tag = soup.find('body')
for i,v in enumerate(tag):
print(i,v)
⑭ is_empty_element,是否是空标签(是否可以是空)或者自闭合标签, 判断是否是如下标签:'br' , 'hr', 'input', 'img', 'meta','spacer', 'link', 'frame', 'base'
# 是否是空标签
tag = soup.find('br')
v = tag.is_empty_element
print(v)
# True
⑮ 当前的关联标签
soup.next
soup.next_element
soup.next_elements
soup.next_sibling
soup.next_siblings tag.previous
tag.previous_element
tag.previous_elements
tag.previous_sibling
tag.previous_siblings tag.parent
tag.parents
⑯ 查找某标签的关联标签
tag.find_next(...)
tag.find_all_next(...)
tag.find_next_sibling(...)
tag.find_next_siblings(...) tag.find_previous(...)
tag.find_all_previous(...)
tag.find_previous_sibling(...)
tag.find_previous_siblings(...) tag.find_parent(...)
tag.find_parents(...) 参数同find_all
⑰ elect,select_one, CSS选择器
soup.select("title")
soup.select("p nth-of-type(3)")
soup.select("body a")
soup.select("html head title")
tag = soup.select("span,a")
soup.select("head > title")
soup.select("p > a")
soup.select("p > a:nth-of-type(2)")
soup.select("p > #link1")
soup.select("body > a")
soup.select("#link1 ~ .sister")
soup.select("#link1 + .sister")
soup.select(".sister")
soup.select("[class~=sister]")
soup.select("#link1")
soup.select("a#link2")
soup.select('a[href]')
soup.select('a[href="http://example.com/elsie"]')
soup.select('a[href^="http://example.com/"]')
soup.select('a[href$="tillie"]')
soup.select('a[href*=".com/el"]')
from bs4.element import Tag
def default_candidate_generator(tag):
for child in tag.descendants:
if not isinstance(child, Tag):
continue
if not child.has_attr('href'):
continue
yield child
tags = soup.find('body').select("a", _candidate_generator=default_candidate_generator)
print(type(tags), tags)
from bs4.element import Tag
def default_candidate_generator(tag):
for child in tag.descendants:
if not isinstance(child, Tag):
continue
if not child.has_attr('href'):
continue
yield child
tags = soup.find('body').select("a", _candidate_generator=default_candidate_generator, limit=)
print(type(tags), tags)
select
⑱ 标签的内容
tag = soup.find('span')
print(tag.string) # 获取
tag.string = 'new content' # 设置
print(soup)
tag = soup.find('body')
print(tag.string)
tag.string = 'xxx'
print(soup)
tag = soup.find('body')
v = tag.stripped_strings # 递归内部获取所有标签的文本
print(v)
⑲ append在当前标签内部追加一个标签
tag = soup.find('body')
v = tag.stripped_strings # 递归内部获取所有标签的文本
print(v)
tag = soup.find('body')
tag.append(soup.find('a'))
print(soup)
from bs4.element import Tag
obj = Tag(name='i',attrs={'id': 'it'})
obj.string = '我是一个新来的'
tag = soup.find('body')
tag.append(obj)
print(soup)
⑳ insert在当前标签内部指定位置插入一个标签
from bs4.element import Tag
obj = Tag(name='i', attrs={'id': 'it'})
obj.string = '我是一个新来的'
tag = soup.find('body')
tag.insert(2, obj)
print(soup)
㉑ insert_after,insert_before 在当前标签后面或前面插入
from bs4.element import Tag
obj = Tag(name='i', attrs={'id': 'it'})
obj.string = '我是一个新来的'
tag = soup.find('body')
# tag.insert_before(obj)
tag.insert_after(obj)
print(soup)
㉒ replace_with 在当前标签替换为指定标签
from bs4.element import Tag
obj = Tag(name='i', attrs={'id': 'it'})
obj.string = '我是一个新来的'
tag = soup.find('div')
tag.replace_with(obj)
print(soup)
㉓ 创建标签之间的关系
tag = soup.find('div')
a = soup.find('a')
tag.setup(previous_sibling=a)
print(tag.previous_sibling)
㉔ wrap将指定标签把当前标签包裹起来
from bs4.element import Tag
obj1 = Tag(name='div', attrs={'id': 'it'})
obj1.string = '我是一个新来的' tag = soup.find('a')
v = tag.wrap(obj1)
print(soup) tag = soup.find('a')
v = tag.wrap(soup.find('p'))
print(soup)
㉕ unwrap,去掉当前标签,将保留其包裹的标签
tag = soup.find('a')
v = tag.unwrap()
print(soup)
Python开发【模块】:BeautifulSoup的更多相关文章
- python开发模块基础:re正则
一,re模块的用法 #findall #直接返回一个列表 #正常的正则表达式 #但是只会把分组里的显示出来#search #返回一个对象 .group()#match #返回一个对象 .group() ...
- python开发模块基础:异常处理&hashlib&logging&configparser
一,异常处理 # 异常处理代码 try: f = open('file', 'w') except ValueError: print('请输入一个数字') except Exception as e ...
- python开发模块基础:os&sys
一,os模块 os模块是与操作系统交互的一个接口 #!/usr/bin/env python #_*_coding:utf-8_*_ ''' os.walk() 显示目录下所有文件和子目录以元祖的形式 ...
- python开发模块基础:序列化模块json,pickle,shelve
一,为什么要序列化 # 将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化'''比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?现在我们能想到的方法就是存在文 ...
- python开发模块基础:time&random
一,time模块 和时间有关系的我们就要用到时间模块.在使用模块之前,应该首先导入这个模块 常用方法1.(线程)推迟指定的时间运行.单位为秒. time.sleep(1) #括号内为整数 2.获取当前 ...
- python开发模块基础:collections模块¶miko模块
一,collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdic ...
- python开发模块基础:正则表达式
一,正则表达式 1.字符组:[0-9][a-z][A-Z] 在同一个位置可能出现的各种字符组成了一个字符组,在正则表达式中用[]表示字符分为很多类,比如数字.字母.标点等等.假如你现在要求一个位置&q ...
- Python开发——目录
Python基础 Python开发——解释器安装 Python开发——基础 Python开发——变量 Python开发——[选择]语句 Python开发——[循环]语句 Python开发——数据类型[ ...
- python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheetahcherrypy:一个WEB frameworkctype ...
- Python爬虫之Beautifulsoup模块的使用
一 Beautifulsoup模块介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Be ...
随机推荐
- pyqt的多Button的点击事件的槽函数的区分发送signal的按钮。
关键函数:QPushButton的setObjectName()/objectName() 个人注解:按功能或者区域,将按钮的点击事件绑定的不同的槽函数上. from PyQt5.QtWidgets ...
- CentOS系统命令
系统命令 yum命令 yum makecache yum 生成缓存 yum list installed mysql* 查看有没有安装过*包 rpm -qa | grep mysql* 查看有没有安装 ...
- 支付宝(移动支付)服务端java版
所需支付宝jar包: sdk2-2.0.jar(点击下载) 工具类目录结构: 点击下载 商户信息已经公钥私钥的配置(公钥私钥的生成与支付宝商户平台配置请看官方文档:https://doc.open ...
- 记录一下我的GDB配置
一:为了更好的在GDB中显示STL容器.我们首先要下载一个python脚本 PS:要确定你所安装的GDB能够运行python脚本 cd ~ mkdir .gdb cd .gdb svn co svn: ...
- CSS3给页面打标签
我们经常会在页面的左上角或者右上角看到类似如图所示的标签,比如页面的链接(最常使用)等,下面我们就实现一个简单的标签 实现步骤是先做一个水平长条,使用CSS3的transform来实现旋转,如果是在左 ...
- 【zookeeper】 zookeeper 集群搭建
集群搭建环境: 发行版:CentOS-6.6 64bit 内核:2.6.32-504.el6.x86_64 CPU:intel-i7 3.6G 内存:2G 集群搭建步骤: 1. 确保机器安装了jdk ...
- [Scikit-learn] Dynamic Bayesian Network - Kalman Filter
看上去不错的网站:http://iacs-courses.seas.harvard.edu/courses/am207/blog/lecture-18.html SciPy Cookbook:http ...
- SQL集合运算:差集、交集、并集
1.差集( except ) select a from t_a except select a from t_b -- 也可写作: select a from t_a where a not in ...
- Python Scrapy初步使用
1.创建爬虫工程 scrapy startproject stockproject001 2.创建爬虫项目 cd stockproject001 scrapy genspider stockinfo ...
- VC项目程序运行时设置指定目录读取Dll
方法一: 选择当前工程,右击"Properties" -> "Configuration Properties" -> "Debuggin ...