1.通常來講,爲了找到BeautifulSoup對象內任何第一個標籤入口,使用find()方法。css
以上代碼是一個生態金字塔的簡單展現,爲了找到第一輩子產者,第一消費者或第二消費者,可使用Beautiful Soup。html
找到第一輩子產者:html5
生產者在第一個<url>標籤裏,由於生產者在整個html文檔中第一個<url>標籤中出現,因此可使用find()方法找到第一輩子產者,在ecologicalpyramid.pypython
中寫入下面一段代碼,使用ecologicalpyramid.html文件建立BeautifulSoup對象。正則表達式
from bs4 import BeautifulSoup with open('ecologicalpyramid.html', 'r') as ecological_pyramid: # ecological 生態系統 pyramid 金字塔 soup = BeautifulSoup(ecological_pyramid) producer_entries = soup.find('ul') print(producer_entries.li.div.string)
輸出結果:plants函數
2.find()url
find函數:spa
find(name, attrs, recursive, text, **wargs) # recursive 遞歸的,循環的regexp
這些參數至關於過濾器同樣能夠進行篩選處理。不一樣的參數過濾能夠應用到如下狀況:orm
經過標籤查找:
能夠傳遞任何標籤的名字來查找到它第一次出現的地方。找到後,find函數返回一個BeautifulSoup的標籤對象。
from bs4 import BeautifulSoup with open('ecologicalpyramid.html', 'r') as ecological_pyramid: soup = BeautifulSoup(ecological_pyramid, 'html') producer_entries = soup.find('ul') print(type(producer_entries))
輸出結果: <class 'bs4.element.Tag'>
經過文本查找:
直接字符串的話,查找的是標籤。若是想要查找文本的話,則須要用到text參數。以下所示:
from bs4 import BeautifulSoup with open('ecologicalpyramid.html', 'r') as ecological_pyramid: soup = BeautifulSoup(ecological_pyramid, 'html') producer_string = soup.find(text = 'plants') print(plants_string)
輸出:plants
經過正則表達式查找:
有如下html代碼:
想找出第一個郵箱地址,可是第一個郵箱地址沒有標籤包含,因此經過其餘方式很難找到。可是能夠將郵箱地址進行正則表達式處理。
import re from bs4 import BeautifulSoup email_id_example = """<br/> <div>The below HTML has the information that has email ids.</div> abc@example.com <div>xyz@example.com</div> <span>foo@example.com</span> """ soup = BeautifulSoup(email_id_example) emailid_regexp = re.compile("\w+@\w+\.\w+") # regexp 表達式對象 first_email_id = soup.find(text=emailid_regexp) print(first_email_id)
輸出結果:abc@example.com
經過標籤屬性進行查找:
上面html代碼,其中第一個消費者在ul標籤裏面且id屬性爲priaryconsumer(priary consumer一次消費者,初級消費者)。
from bs4 import BeautifulSoup with open('ecologicalpyramid.html', 'r') as ecological_pyramid: soup = BeautifulSoup(eccological_pyramid, 'html') primary_consumer = soup.find(id='primaryconsumers') print(primary_consumer.li.div.string)
輸出結果:deer
基於定製屬性查找:
經過標籤屬性查找的方式適用大多數標籤屬性,包括id,style,title,但有 「-」,Class標籤屬性例外。
好比html5標籤中的data-custom屬性,若是咱們這樣
customattr = """<p data-custom='custom'>custo attribute example</p> """ customsoup = BeautifulSoup(customattr, 'lxml') customSoup.find(data-custom="custom")
那麼則會報錯。緣由是在python中變量不能含有"-"這個字符,而咱們傳遞的data-custom有這個字符。
解決辦法是在attrs屬性用字典進行傳遞參數。
using_attrs = customsoup.find(attrs={'data-custom':'custom'}) print(using_attrs)
基於css類的查找:
class是python的保留關鍵字,因此沒法使用class這個關鍵字。
第一種方法:在attrs屬性用字典進行傳遞參數
css_class = soup.find(attrs={'class':'primaryconsumers'}) print(css_class)
第二種方法:BeautifulSoup中的特別關鍵字參數class_。
css_class = soup.find(class_ = 'primaryconsumers')
基於定義的函數進行查找:
能夠傳遞函數到find()來基於函數定義的條件查找。函數必須返回True或False。
def is_secondary_consumers(tag): return tag.has_attr('id') and tag.get('id') == 'secondaryconsumers'
secondary_consumer = soup.find(is_secondary_consumers) print(secondary_consumer.li.div.string)
輸出:fox
將方法進行組合後進行查找:
能夠用其中任何方法進行組合進行查找,好比同時基於標籤名和id號。
3.find_all查找
find()查找第一個匹配結果出現的地方,find_all()找到全部匹配結果出現的地方。
查找全部3級消費者:
all_tertiaryconsumers = soup.find_all(class_ = 'tertiaryconsumerslist') # tertiary第三的
其中all_tertiaryconsumers的類型是列表。
因此對其列表進行迭代,循環輸出三級消費者的名字。
for tertiaryconsumer in all_tertiaryconsumers: print(tertiaryconsumer.div.string)
輸出結果:
lion
tiger
find_all()的參數:
find_all(name, attrs, recursive, text, limit, **kwargs)
limit參數能夠限制獲得的結果的數目。
參照前面的郵件地址例子,獲得全部郵件地址:
email_ids = soup.find_all(text=emailid_regexp) print(email_ids)
輸出結果:[u'abc@example.com',u'xyz@example.com',u'foo@example.com']
使用limit參數:
email_ids_limited = soup.find_all(text=emailid_regexp, limit = 2) print(email_ids_limited)
限制獲得兩個結果,因此輸出結果:[u'abc@example.com',u'xyz@example.com']
能夠向find函數傳遞True或False參數,若是傳遞True給find_all(),則返回soup對象的全部標籤。對於find()來講,則返回soup對象的第一個標籤。
all_texts = soup.find_all(text=True) print(all_texts)
輸出結果:
一樣,能夠在傳遞text參數時傳遞一個字符串列表,那麼find_all()會找到挨個在列表中定義過的字符串。
all_texts_in_list = soup.find_all(text=['plants', 'algae']) print(all_texts_in_list)
輸出結果:
[u'plants', u'alage']
這個一樣適用於查找標籤,標籤屬性,定製屬性和CSS類。如:
div_li_tags = soup.find_all(['div', 'li'])
而且find()和find_all()都會查找一個對象全部後輩們,不過能夠經過recursive參數控制。(recursive迴歸,遞歸)
若是recursive=False,只會找到該對象的最近後代。
經過標籤之間的關係進行查找
查找父標籤
經過find_parents()或find_parent()。它們之間的不一樣相似於find()和find_all()的區別。
find_parents()返回所有的相匹配的父標籤,而find_parent()返回最近一個父標籤。適用於find()的方法一樣適用於這兩個方法。
在第一消費者例子中,能夠找到離Primaryconsumer最近的ul父標籤。
primaryconsumers = soup.find_all(class_ = 'primaryconsumerlist') primaryconsumer = primaryconsumers[0] parent_ul = primaryconsumer.find_parents('ul') print(parent_ul)
一個簡單的找到一個標籤的父標籤的方法是使用find_parent()卻不帶任何參數。
immediateprimary_consumer_parent = primary_consumer.find_parent()
查找同胞
標籤在同一個等級,這些標籤是同胞關係,好比參照上面金子塔例子,全部的ul標籤就是同胞的關係。上面的ul標籤下的producers,primaryconsumers,,
secondaryconsumers,teriaryconsumers就是同胞關係。
div下的plants和algae不是同胞關係,可是plants和臨近的number是同胞關係。
Beautiful Soup自帶查找同胞的方法。
好比find_next_siblings()和find_next_sibling()查找對象下面的同胞。(sibling兄弟姐妹)
producers = soup.find(id = 'producers') next_siblings = producers.find_next_siblings() print(next_siblings)
輸出結果將會輸出與之臨近的下面的全部同胞html代碼。
查找下一個
對每個標籤來講,下一個元素可能會是定位字符串,標籤對象或者其餘BeautifulSoup對象,咱們定義下一個元素爲當前元素最靠近的元素 。
這不用於同胞定義,咱們有方法能夠找到咱們想要標籤的下一個其餘元素對象。find_all_next()找到與當前元素最靠近的全部對象。而find_next()找到離當前元素最接近的對象。
好比,找到在第一個div標籤後的全部li標籤
first_div = soup.div all_li_tags = first_div.find_all_next('li')
查找上一個
與查找下一個相反的是查找前一個,用find_previous()和find_all_previous()。