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 ...
随机推荐
- Spring-Resource接口
4.1.1 概述 在日常程序开发中,处理外部资源是很繁琐的事情,我们可能需要处理URL资源.File资源资源.ClassPath相关资源.服务器相关资源(JBoss AS 5.x上的VFS资源)等等很 ...
- TODO的用法
visual studio提供//TODO标记,不过不会在右边标记处明显标识,需要你选择菜单栏的视图进行查看.方法如下: 1.首先在你还未完成的地方打上TODO标记,以下方式均可: 1)//TODO: ...
- 用ADO操作数据库的方法步骤
用ADO操作数据库的方法步骤 学习ADO时总结的一些经验 - 技术成就梦想 - 51CTO技术博客 http://freetoskey.blog.51cto.com/1355382/989218 ...
- idea-java项目配置
导入项目后,工程结构配置: 如果不加入tomcat 运行库,项目会报servlet jar 找不到的异常 tomcat服务器配置
- SQLServer------插入数据时出现IDENTITY_INSERT错误
详细错误信息: 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'Student' 中的标识列插入显式值. 原因: 表中存在某个字段是自动增长的标识符 解决方法: set IDENT ...
- 开源 免费 java CMS - FreeCMS1.9 移动APP生成网站列表数据
项目地址:http://www.freeteam.cn/ 生成网站列表数据 提取同意移动APP訪问的网站列表,生成json数据到/mobile/index.html页面. 从左側管理菜单点击生成网站列 ...
- leetcode -- permutation 总结
leetcode上关于permutation有如下几题 Permutation Sequence Next Permutation Permutations Permutations II
- Dubbo(一) -- 初体验
Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,是阿里巴巴SOA服务化治理方案的核心框架. 一.Dubbo出现的背景 随着互联网的发展,网站应用的规模不断扩大,常规的 ...
- (二)微信小程序的三种传值方式
1.全局变量 app.js里 App({ //全局变量 globalData: { userInfo: null, host: 'http://localhost:8080/data.json' } ...
- Xcode模版生成文件头部注释
在使用Xcode创建工程或者新建类的时候,顶部都会有一些xcode帮我们生成的注释 //// MySingletonClass.h// 单例模式//// Created by mark on 15/8 ...