beautifulsoup 用于提取抓取的html 字符串的标签
官网文档上的函数丰富,从上边找到的东西
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-parents-and-find-parent
1四类对象
Beautiful Soup 将复杂HTML文档转换成一个复杂的树形结构,每个节点都是 Python 对象,所有对象可以归纳为4种:
- Tag
- NavigableString
- BeautifulSoup
- Comment
2函数
find_all()
find()
find_parents() , find_parent()
find_next_siblings() ,find_next_sibling()
find_previous_siblings() ,find_previous_sibling()
find_all_next() ,find_next()
find_all_previous() , find_previous()
find(name,attrs,recursive,text,**wargs)
这些参数相当于过滤器一样可以进行筛选处理。
不同的参数过滤可以应用到以下情况:
一下查找方法可以组合查找
- 查找标签,基于name参数
- 查找文本,基于text参数
- 基于正则表达式的查找
- 查找标签的属性,基于attrs参数
- 基于函数的查找
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</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.</p> <p class="story">...</p> """
soup=BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8')
基于标签 和 属性查找
link_node = soup.find('a',href='http://example.com/tillie')
其中class为python关键字,关于class查找
查找class=‘mark’可以写成
1
link_node = soup.find(class_=mark)
2
link_node = soup.find(attrs={'class':'mark'})
其中方法2也可以作为查找其他跟python关键字或者命名规则有冲突的属性查找
基于文本查找
link_node = soup.find(text="plants")
基于标签 和正则查找
link_node = soup.find('a',href=re.compile(r"lac"))
基于函数查找
def id_text_de(tag):
return tag.name=='a' and tag.get_text()=='Elsie'
link_node = soup.find(id_text_de)
find_all(name,attrs, recursive, string, limit, **kwargs)
find_all
就多了一个limit
跟数据库那个limit差不多
其他查找父子兄弟节点函数
相当于find缩小了查询范围,用法基本一致