Beautiful Soup

Beautiful Soup 是解析,遍历,维护“标签树”的功能库。

官网

https://www.crummy.com/software/BeautifulSoup/

中文说明

http://beautifulsoup.readthedocs.io/zh_CN/latest/

安装:

pip install beautifulsoup4

from bs4 import Beautiful Soup

soup = BeautifulSoup('<p>data</p>', 'html.parser')
soup2 =BeautifulSoup(open("D://example.html"), 'html.parser')

解析器

 解析器  使用方法 条件 
 bs4的HTML解析器  BeautifulSoup(mk, 'html.parse')  安装bs4
 lxml的HTML解析器  BeautifulSoup(mk, 'lxml') pip install lxml 
 lxml的XML解析器  BeautifulSoup(mk, 'xml') pip install lxml 
 html5lib的解析器  BeautifulSoup(mk, 'html5lib') pip install html5lib 

 基本元素:

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用<></>标明开头和结尾
Name 标签的名字
Attributes 标签的属性
NavigableString 标签内非属性字符串
Comment 标签内字符串的注释部分,一种特殊的comment类型

soup.tag

soup.tag.name (返回标签的名字,字符串  soup.tag.parent.name)

soup.tag.attrs(返回字典  soup.tag.attrs['class'])

soup.tag.string (NavigableString 可以跨越多个标签层次 Notice comment 和 string 需要用类型来判断)

soup.p
soup.p.name
soup.p.attrs
soup.p.string
examole1

bs4库遍历HTML文件:

下行遍历:从根节点到叶子节点

上行遍历:

平行遍历:平行遍历发生在同一个父节点下的各节点间

.contents 子节点的列表

.children 子节点的迭代类型

.descendants 子孙节点的所有迭代类型

.parent 返回父节点

.parents 节点先辈标签的迭代类型

.next_sibling

.previous_sibling

.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签

.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

 相关方法:

soup.prettify()/soup.tag.prettify()

soup.find_all(tag)  <>.find_all(name,attrs,recursive,string,**kwargs)   返回列表类型,存储查找的结果  结合re库

          name:对标签名称的检索字符串或字符串列表,if 为 ture,检索所有标签

          attrs:对标签属性值的检索字符串,可标注属性检索  soup.find_all('p', 'course')属性值为course的p标签  soup.find_all(id='link1')id为link1的所有标签

          recursive:是否对子孙全部检索,默认True。如果为False,则值检索儿子节点

          string:<>...</>中字符串区域的检索字符串。类似于Ctrl + F

        <tag>(...) 等价于 <tag>.find_all(...)

        soup(...) 等价于 soup.find_all(...)

          

<>.get(attr) 获取属性值


原文地址:https://www.cnblogs.com/jinggo/p/7697827.html