python3 BeautifulSoup模塊


一、安裝下載:

1、安裝:
pip install beautifulsoup4

2、可選擇安裝解析器:
pip install lxml
pip install html5lib

3、解析器比較:
解析器 使用方法 優勢 劣勢
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"])

BeautifulSoup(markup, "xml")

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

 二、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#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM