BeautifulSoup
BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单。
1 | from bs4 import BeautifulSoup |
安装:
1 | pip3 install beautifulsoup4 |
使用示例:
1 | from bs4 import BeautifulSoup |
name 标签名称
1 | tag = soup.find('a') |
attr 标签属性
1 | tag = soup.find('a') |
children 所有子标签
1 | body = soup.find('body') |
descendants 所有子子孙孙标签
1 | body = soup.find('body') |
clear 将标签的所有子标签全部清空(保留标签名)
1 | tag = soup.find('body') |
decompose 递归的删除所有的标签
1 | body = soup.find('body') |
extract 递归的删除所有的标签,并获取删除的标签
1 | body = soup.find('body') |
decode 转换为字符串(含当前标签);decode_contents(不含当前标签)
1 | body = soup.find('body') |
encode 转换为字节(含当前标签);encode_contents(不含当前标签)
1 | body = soup.find('body') |
find 获取匹配的第一个标签
1 | tag = soup.find('a') |
find_all 获取匹配的所有标签
1 | tags = soup.find_all('a') |
has_attr 检查标签是否具有该属性
1 | tag = soup.find('a') |
get_text 获取标签内部文本内容
1 | tag = soup.find('a') |
index 检查标签在某标签中的索引位置
1 | tag = soup.find('body') |
is_empty_element 是否是空标签(是否可以是空)或者自闭合标签
判断是否是如下标签:’br’ , ‘hr’, ‘input’, ‘img’, ‘meta’,’spacer’, ‘link’, ‘frame’, ‘base’
1 | tag = soup.find('br') |
当前的关联标签
1 | # soup.next |
查找某标签的关联标签
1 |
select,select_one, CSS选择器
1 | soup.select("title") |
标签的内容
1 | tag = soup.find('span') |
append 在当前标签内部追加一个标签
1 | tag = soup.find('body') |
insert在当前标签内部指定位置插入一个标签
1 | from bs4.element import Tag |
insert_after,insert_before 在当前标签后面或前面插入
1 | from bs4.element import Tag |
replace_with 在当前标签替换为指定标签
1 | from bs4.element import Tag |
创建标签之间的关系
1 | tag = soup.find('div') |
wrap 将指定标签把当前标签包裹起来
1 | from bs4.element import Tag |
unwrap 去掉当前标签,将保留其包裹的标签
1 | tag = soup.find('a') |