Beautiful Soup庫的簡單使用

一、BeautifulSoup庫的簡單使用

import requests
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
from bs4 import BeautifulSoup  #導入BeautifulSoup庫
soup=BeautifulSoup(demo,"html.parser")  #使用html.parser進行解析
print(soup.prettify())  #打印解析結果

BeautifulSoup對應一個HTML/XML文檔的全部內容

BeautifulSoup===標籤樹===BeautifulSoup類

二、BeautifulSoup標籤的簡單使用

使用下述.name,.attrs等訪問名稱,屬性等:

基於bs4庫的HTML內容遍歷方法:

簡單代碼:

import requests
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
from bs4 import BeautifulSoup  #導入BeautifulSoup庫
soup=BeautifulSoup(demo,"html.parser")  #使用html.parser進行解析
print(soup.title)  #若有多個類似標籤,僅返回第一個
print(soup.a)
print(soup.a.name)   #返回名字
print(soup.a.parent.name)

tag=soup.a
print(tag.attrs)   #屬性
print(tag.attrs['class'])
print(tag.string)   #兩個尖括號之間的內容
print(type(tag.string))

print(soup.head)
print(soup.head.contents)   #contents返回其兒子

print(soup.title.parent)  #返回父節點

三、基於bs4庫的HTML內容查找方法

如:

soup.find_all(string='Basic Python')
soup.find_all(id=re.compile('link'))   #正則表達式的模糊查詢

擴展方法:

 

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