Beautiful Soup
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
- 按照标准的缩进格式的结构输出:soup.prettify()
- 获得第一个寻找的标签 soup.p
- 获得标签之间的内容 soup.p.string
- 获得寻找标签的父标签 soup.title.parent
- 获得所有的标签 soup.find_all(‘a’)
- 得到元素的值 soup.find(title=“爱思助手”).get(‘class’)
- 从文档中获取所有文字内容soup.get_text()
- 任何HTML或XML文档都有自己的编码方式,比如ASCII 或 UTF-8,但是使用Beautiful Soup解析后,文档都被转换成了Unicode;
- 自动检测识识别文档的编码 soup.original_encoding
- 机器的解析方式 BeautifulSoup(markup, “html.parser”)
- 指定被解析的文件的编码方式 BeautifulSoup(markup, from_encoding=“iso-8859-8”)
- 取得标签的某个属性值 p[‘class’]
- sttribute 的属性值的修改和删除 del tag[‘class’]; tag[‘class’]=‘verybold’
find
- find( name , attrs , recursive , text , **kwargs )
- find() 方法直接返回结果,没有找到结果返回None
find_all()
- find_all( name , attrs , recursive , text , **kwargs )
- find_all() 方法的返回结果是值包含一个元素的列表,没有找到返回一颗空列表
- name 为标签的名字
- attrs 为根据属性来进行寻找,可以是字典
- recursive =False 可以只搜索直接子节点
- text 根据文本进行筛选
- limit 使用参数限制返回结果的数量 soup.find_all(“a”, limit=2)
- find_all() 方法的返回结果是值包含一个元素的列表
- find_all(‘b’)正确 find_all(‘class’)错误 只能寻找标签名
- find_all(re.compile(‘t’))和正则表达式结合