爬蟲:基於bs4庫的html內容查詢方法
阿新 • • 發佈:2018-11-25
<>.find_all(name,attrs,recursive,string,**kwargs)
返回一個列表型別,儲存查詢的結果。
name:對標籤名稱的檢索字串
attrs:對標籤屬性值得檢索字串,可標註屬性檢索
recursive:是對子孫全部檢索,預設True
呼叫tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜尋tag的直接子節點,可以使用引數 recursive=False .
string:<>...</>中字串區域的檢索字串
一些具體案例可參考:https://www.cnblogs.com/zipon/p/6129280.html
>>> from bs4 import BeautifulSoup >>> import requests >>> r=requests.get("https://www.baidu.com/?tn=98012088_5_dg&ch=12") >>> demo=r.text >>> soup=BeautifulSoup(demo,"html.parser") >>> for link in soup.find_all('a'): print(link.get('href')) //找到所有a標籤的href連結 >>> soup.find_all('a') //找到所有的a標籤 >>> soup.find_all(['a','b']) //找到所有的a、b標籤 >>> for tag in soup.find_all(True): print(tag.name) //查詢所有的標籤並打印出名字
demo='<p class="course">Python is a wonderful general-purpose programming language </p>' soup=BeautifulSoup(demo,"html.parser") soup.find_all('p','course') //查詢p標籤屬性值為course的內容 soup.find_all(id='link1') //查詢id=link1的內容 soup.find_all(id='link') import re //匯入正則表示式模組 soup.find_all(id=re.compile('link')) //輸出以link開頭但是與link不完全一致的標籤資訊
<tag>(..)等價於<tag>.find_all(..)
soup(..)等價於 soup.find_all(..)
擴充套件方法
方法 | 說明 |
<>.find() | 搜尋且只返回一個結果,字串型別,同.find_all()引數 |
<>.find_parents() | 在先輩節點中搜索,返回列表型別,同.find_all()引數 |
<>.find_parent() | 在先輩節點中返回一個結果,字串型別,桐.find()引數 |
<>.find_next_siblings() | 在後續平行節點中搜索,返回列表型別,同.find_all()引數 |
<>.find_next_sibling() | 在後續平行節點中返回一個結果,字串型別,同.find()引數 |
<>.find_previous_siblings() | 在前序平行節點中搜索,返回列表型別,同.find_all()引數 |
<>.find_previous_sibling() | 在前序平行節點中返回一個結果,字串型別,同.find引數 |