Beautiful Soup 是一個能夠從HTML或XML文件中提取數據的Python庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.html
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>
"""
方式一: 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.文本查找spa
經過文本查找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.正則查找code
經過正則查找全部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.列表orm
經過列表查找全部的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.Truexml
獲取全部標籤 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.方法htm
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))