BeautifulSoup解析模块

时间:2023-03-09 14:35:39
BeautifulSoup解析模块

简介:

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.

使用

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p> <p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
"""

生成beautifulSoup对象:

方式一:
soup = BeautifulSoup(html_doc, "lxml")
print(soup) 方式二:
soup = BeautifulSoup(open('a.html'), "lxml")
print(soup) soup = BeautifulSoup(html_doc, "lxml")

常用获取方法:

自动补全
soup.prettify() print(soup.p)
获取p标签下的b标签
print(soup.p.b)
获取p标签下的b标签下的文本
print(soup.p.b.text) 找body内的所有标签
print(soup.body.contents) 获取p标签属性
print(soup.p.attrs) 获取p标签的孩子, 返回一个iter对象
print(list(soup.p.children)) 获取p标签的子子孙孙
print(list(soup.p.descendants)) 获取p标签的爸爸
print(soup.p.parent) 获取p标签的爸爸, 获取p标签的爸爸的爸爸, 获取p标签的爸爸的爸爸的爸爸
print(list(soup.p.parents)) 获取a标签内的href属性
print(soup.a.attrs['href'])

五种过滤器:

搜索文档树
1.文本查找

通过文本查找p标签
print(soup.find_all(name='p')) 通过文本查找文本为$37的p标签
print(soup.find_all(name='p', text='$37')) 通过文本查找id为link3的a标签
print(soup.find_all(name='a', attrs={"id": "link3"}))

2.正则查找

通过正则查找所有p标签

import re
print(soup.find_all(name=re.compile("^p"))) 通过正则查找所有a标签
print(soup.find_all(name=re.compile("^a"))) 通过正则查找所有id为link的p标签
print(soup.find_all(name="p", attrs={"id": re.compile("^link")})) 通过正则查找所有id为link的a标签
print(soup.find_all(name="a", attrs={"id": re.compile("^link")})) 通过正则查找所有class为story的p标签
print(soup.find_all(name="p", attrs={"class": re.compile("story")}))

3.列表

通过列表查找所有的a、p标签
print(soup.find_all(name=['p', 'a'])) 通过列表查找所有的正则匹配有Elsie的文本
print(soup.find_all(text=[re.compile("Elsie")])) 通过列表查找所有的正则匹配有Elsie的文本的a标签
print(soup.find_all(name=['a'], text=[re.compile("Elsie")])

4.True

获取所有标签
print(soup.find_all(name=True)) 获取所有有id的a标签
print(soup.find_all(name="a", attrs={"id": True})) # 获取所有有class的a标签
print(soup.find_all(name="a", attrs={"class": True}))

5.方法

def have_id_not_class(a):
# if tag.has_attr('id') and not tag.has_attr('class'):
# return tag
if a.has_attr('class') and not a.has_attr('id'):
return a 通过方法查找所有有class没id的标签
print(soup.find_all(have_id_not_class))