如何使用bs4爬蟲解析html

  • Beautiful Soup簡介
  • Beautiful Soup安裝
  • Beautiful Soup用法

Beautiful Soup簡介

  • 官方網址:https://beautifulsoup.readthedocs.io/zh_CN/latest/
  • Beautiful Soup是一個可以從HTML文件中提取數據的Python庫,它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式
  • 在接口測試中用於驗證頁面內容的正確性

Beautiful Soup安裝

  • Windows 下命令行輸入:pip install beautifulsoup4 即可。

Beautiful Soup用法

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,"html.parser")
print soup
print type(soup)
print soup.prettify()# 按照標準的縮進格式的結構輸出
# 通過標籤名稱來獲取Tag對象,如果有多個相同的標籤名稱,返回第一個
print soup.html
print soup.body
print soup.title
print type(soup.title)# class類,tag標籤
print soup.find_all('a')# 查找所有a標籤
print soup.find_all('a')[2]# 查找第二個a標籤
print soup.title.string# 輸出字符串格式String
print soup.b.string # 輸出註釋

#find只返回第一個
print soup.find("id='''")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章