1、安裝:
pip install beautifulsoup4
二、可選擇安裝解析器:
pip install lxml
pip install html5lib
三、解析器比較:
解析器 |
使用方法 |
優點 |
劣勢 |
Python標準庫 |
BeautifulSoup(markup, "html.parser") |
- Python的內置標準庫
- 執行速度適中
- 文檔容錯能力強
|
- Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差
|
lxml HTML 解析器 |
BeautifulSoup(markup, "lxml") |
|
|
lxml XML 解析器 |
BeautifulSoup(markup, ["lxml", "xml"])html BeautifulSoup(markup, "xml")html5 |
|
|
html5lib |
BeautifulSoup(markup, "html5lib") |
- 最好的容錯性
- 以瀏覽器的方式解析文檔
- 生成HTML5格式的文檔
|
|
|
|
|
|
from bs4 import BeautifulSoupimport requests,rereq_obj = requests.get('https://www.baidu.com')soup = BeautifulSoup(req_obj.text,'lxml')'''標籤查找'''print(soup.title) #只是查找出第一個print(soup.find('title')) #效果和上面同樣print(soup.find_all('div')) #查出全部的div標籤'''獲取標籤裏的屬性'''tag = soup.divprint(tag['class']) #多屬性的話,會返回一個列表print(tag['id']) #查找標籤的id屬性print(tag.attrs) #查找標籤全部的屬性,返回一個字典(屬性名:屬性值)'''標籤包的字符串'''tag = soup.titleprint(tag.string) #獲取標籤裏的字符串tag.string.replace_with("哈哈") #字符串不能直接編輯,能夠替換'''子節點的操做'''tag = soup.headprint(tag.title) #獲取head標籤後再獲取它包含的子標籤'''contents 和 .children'''tag = soup.bodyprint(tag.contents) #將標籤的子節點以列表返回print([child for child in tag.children]) #輸出和上面同樣'''descendants'''tag = soup.body[print(child_tag) for child_tag in tag.descendants] #獲取全部子節點和子子節點'''strings和.stripped_strings'''tag = soup.body[print(str) for str in tag.strings] #輸出全部全部文本內容[print(str) for str in tag.stripped_strings] #輸出全部全部文本內容,去除空格或空行'''.parent和.parents'''tag = soup.titleprint(tag.parent) #輸出便籤的父標籤[print(parent) for parent in tag.parents] #輸出全部的父標籤'''.next_siblings 和 .previous_siblings 查出全部的兄弟節點''''''.next_element 和 .previous_element 下一個兄弟節點''''''find_all的keyword 參數'''soup.find_all(id='link2') #查找全部包含 id 屬性的標籤soup.find_all(href=re.compile("elsie")) #href 參數,Beautiful Soup會搜索每一個標籤的href屬性:soup.find_all(id=True) #找出全部的有id屬性的標籤soup.find_all(href=re.compile("elsie"), id='link1') #也能夠組合查找soup.find_all(attrs={"屬性名": "屬性值"}) #也能夠經過字典的方式查找