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))