python3 BeautifulSoup模塊

1、安裝下載:

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")
  • 速度快
  • 文檔容錯能力強
  • 須要安裝C語言庫
lxml XML 解析器

BeautifulSoup(markup, ["lxml", "xml"])html

BeautifulSoup(markup, "xml")html5

  • 速度快
  • 惟一支持XML的解析器
  • 須要安裝C語言庫
html5lib BeautifulSoup(markup, "html5lib")
  • 最好的容錯性
  • 以瀏覽器的方式解析文檔
  • 生成HTML5格式的文檔
  • 速度慢
  • 不依賴外部擴展
 
   

 2、BS的使用:

from bs4 import BeautifulSoup
import requests,re
req_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.div
print(tag['class']) #多屬性的話,會返回一個列表
print(tag['id']) #查找標籤的id屬性
print(tag.attrs) #查找標籤全部的屬性,返回一個字典(屬性名:屬性值)

'''標籤包的字符串'''
tag = soup.title
print(tag.string) #獲取標籤裏的字符串
tag.string.replace_with("哈哈") #字符串不能直接編輯,能夠替換

'''子節點的操做'''
tag = soup.head
print(tag.title) #獲取head標籤後再獲取它包含的子標籤

'''contents 和 .children'''
tag = soup.body
print(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.title
print(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={"屬性名": "屬性值"}) #也能夠經過字典的方式查找

 更多詳細的用法:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#瀏覽器

相關文章
相關標籤/搜索