2. find() 和 find_all()
推薦有能力的各位查看BeautifulSoup官方文檔唇聘,這里簡(jiǎn)單講解一下妖混。
請(qǐng)看以下比較:
find_all(tag, attributes, recursive, text,limit, keywords)
# find_all(標(biāo)簽, 屬性, 遞歸, 文本,限制查詢數(shù)量, 關(guān)鍵字)
find(tag,attributes, recursive, text,keywords)
#find 相當(dāng)于find_all(,limit=1)
絕大多數(shù)的情況我們只會(huì)遇到前兩個(gè)參數(shù)绒窑,tag和attributes僧诚。tag和attributes都可以查找多個(gè)值丸逸。
from urllib.request import urlopen
from bs4 import BeautifulSoup
url ='http://www.pythonscraping.com/pages/warandpeace.html'
html= urlopen(url) #抓取了該url網(wǎng)頁(yè)
soup = BeautifulSoup(html) #使用BeautifulSoup對(duì)網(wǎng)頁(yè)進(jìn)行解析
hs = soup.find_all({'h1', 'h2'})#find_all抓取所有綠色字體某饰,返回list
print(hs)
得到結(jié)果:
[<h1>War and Peace</h1>, <h2>Chapter 1</h2>]
同理儒恋,屬性參數(shù)也可以包含多個(gè)屬性。例如需要查找所有綠色和紅色的文本:
....
words = soup.find_all('span', {'class':{'green', 'red'}})
print(len(words))
有興趣的朋友可以看看綠色和紅色的tag分別有多少個(gè)黔漂。
關(guān)鍵字參數(shù)可以用來(lái)選擇包含特定屬性的是標(biāo)簽诫尽,比如:
all_text = soup.find_all(id = 'text')
print(all_text[0].get_text()
細(xì)心的朋友可能會(huì)注意到,其實(shí)關(guān)鍵字參數(shù)匹配完全可以用屬性參數(shù)替換炬守。
soup.find_all(id='text')
soup.find_all("",{"id":"text"})
soup.find_all(class="green")
soup.find_all('',{'class':'green'})
注意: 在BeautifulSoup4版本中find_all 和findAll 是一樣的牧嫉。find_all是新版本的寫法,findAll是舊版本的寫法减途,但是目前二者在版本4中通用酣藻。