文章目錄
遍歷文檔樹
演示文檔(愛麗絲夢遊仙境的一段內容)
from bs4 import BeautifulSoup
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')
"""
tag.contents
tag的 contents 屬性可以將tag的子節點以列表的方式輸出
print(soup.body.contents)
可以通過列表的方法來獲取某個元素的屬性
print(soup.body.contents[1].name)
tag.children
獲取tag的所有子節點並返回一個生成器,可用於迭代
for child in soup.body.children:
print(child)
print('------------------------------')
tag.descendants
獲取tag的所有子孫節點
tag.strings
如果tag中包含多個字符串,即子孫節點中的內容可以用此獲取後進行遍歷
tag…stripped_strings
與tag.strings 用法一致,不同的是會去除多餘的空白
tag.parent
獲取tag的父節點
tag.parents
獲取tag的父輩元素的所有節點,返回一個生成器
tag.previous_sibling
獲取當前tag的上一節點,真實結果是當前標籤與上一個標籤之間的頓號和換行符
tag.next_sibling
獲取tag的下一個節點,結果是當前標籤與下一標籤之間的頓號或換行符
tag.previous_siblings
獲取tag的兄弟節點,返回一個生成器(用法見
tag.children)
tag.next_siblings
獲取當前Tag的下一節點的所有兄弟節點,返回一個生成器**
tag.previous_element
獲取解析過程中上一個被解析的對象(字符串或tag)
tag.next_element
獲取解析過程中下一個被解析的對象(字符串或tag)
tag.previous_elements
向前訪問文檔的解析內容,返回一個生成器
tag.next_elements
向後訪問文檔的解析內容,返回一個生成器
tag.has_attr
判斷tag是否有含有屬性
搜索文檔樹
常用於搜索文檔中的某些內容
演示文檔(愛麗絲夢遊仙境的一段內容)
from bs4 import BeautifulSoup
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')
"""
find_all(name,attrs,recursive,string,limit,**kwargs)
搜索當前節點的所有子節點,孫子節點等
-
name:查找所有名字爲 name 的tag,name可接受的參數爲字符串、正則表達式、列表、True
傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容
#字符串 find_a=soup.find_all('a') print(find_a)
如果傳入正則表達式作爲參數,Beautiful Soup會通過正則表達式的 match() 來匹配內容
#正則表達式 import re for tag in soup.find_all(re.compile("^b")): print(tag.name)
如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回
#列表 soup.find_all(["a", "p"])
可以匹配所有tag
#True for tag in soup.find_all(True): print(tag.name)
-
attrs:有些tag屬性在搜索不能使用,比如HTML5中的 data-* 屬性,定義一個字典參數來搜索包含特殊屬性的tag
直接查詢data-*屬性會報錯
t_list = soup.find_all(data-foo="value")
使用attr參數定義字典查找data-*屬性
t_list = bs.find_all(attrs={"data-foo":"value"}) for item in t_list: print(item)
-
recursive:調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點,可以使用參數 recursive=False .
find_a=soup.find_all('title') print(find_a) find_a=soup.find_all('title',recursive=False) print(find_a)
-
string:通過 string 參數可以搜索文檔中的字符串內容.與 name 參數的可選值一樣, string 參數接受 字符串 , 正則表達式 , 列表, True
#字符串 print(soup.find_all(string="Elsie"))
#列表 print(soup.find_all(string=["Tillie", "Elsie", "Lacie"]))
#正則表達式 print(soup.find_all(string=re.compile("sisters")))
#True print(soup.find_all(string=True))
-
limit:參數限制返回結果的數量
print(soup.find_all('a',limit=2))
-
** kwargs:如果一個指定名字的參數不是find_all()內置的參數名,搜索時會把該參數當作指定名字tag的屬性來搜索
print(soup.find_all(id='link1'))
find_all(name,attrs,recursive,string,**kwargs)
find()與find_all()用法一致,唯一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回符合條件的第一個Tag
find_parents( name , attrs , recursive , string , **kwargs )
搜索當前節點的父輩節點,返回結果是值包含一個元素的列表
a_string = soup.find(string="Lacie")
print(a_string.find_parents('p'))
find_parent( name , attrs , recursive , string , **kwargs )
搜索當前節點的父輩節點,直接返回第一個結果
a_string = soup.find(string="Lacie")
print(a_string.find_parent('p'))
CSS選擇器
Beautiful Soup支持大部分的CSS選擇器,在 Tag 或 BeautifulSoup 對象的 .select() 方法中傳入字符串參數, 即可使用CSS選擇器的語法找到tag
演示文檔(愛麗絲夢遊仙境的一段內容)
from bs4 import BeautifulSoup
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')
"""
通過標籤名查找
print(soup.select('title'))
print(soup.select('p'))
通過id名查找
print(soup.select("#link1"))
print(soup.select('#link2'))
通過class名查找
print(soup.select(".sister"))
print(soup.select("[class~=sister]"))
通過標籤逐層查找
print(soup.select("html head title"))
print(soup.select('body a'))
查找某標籤的直接子標籤
print(soup.select("head > title"))
print(soup.select('p > b'))
查找某標籤的兄弟節點標籤
#匹配所有
print(soup.select("#link1 ~ .sister"))
#匹配一個
print(soup.select("#link1 + .sister"))
混合查找:匹配其中一個即可
print(soup.select("#link1,#link2"))
查詢是否存在某屬性,沒有的返回空列表
print(soup.select('a[href]'))
print(soup.select('a[mm]'))
通過屬性值來查找
print(soup.select('a[href="http://example.com/elsie"]'))
print('--------------------------------------')
print(soup.select('a[href^="http://example.com/"]'))
print('--------------------------------------')
print(soup.select('a[href$="tillie"]'))
print('--------------------------------------')
print(soup.select('a[href*=".com/el"]'))
獲取標籤內容
print(soup.select(".sister")[0].get_text())
print(soup.select(".sister")[1].get_text())