python爬蟲之bs4的基本使用

2021-09-24 13:04:02 字數 1472 閱讀 3096

beautifulsoup可以很方便地查詢html標籤以及其中的屬性和內容

import requests

from bs4 import beautifulsoup

# 建立beautifulsoup物件

# 當資料**為本地檔案時

file

=open

("***.html"

)soup = beautifulsoup(

file

,"lxml"

)# 當資料**為網路時

content = requests.get(

"url請求"

).text

soup = beautifulsoup(content,

"lxml"

)#1 按標籤名查詢標籤

soup.a # 獲取第乙個匹配到的標籤

#2 屬性

soup.a.attrs # 獲取標籤中所有屬性名與對應屬性值的字典

soup.a.attrs[

"屬性名"

]# 獲取屬性名對應的屬性值

soup.a.

["屬性名"

]# 獲取屬性名對應的屬性值的簡寫

soup.a.string # 獲取第乙個匹配到的標籤的內容

soup.a.text # 獲取第乙個匹配到的標籤以及其所包含的子標籤的所有內容

#3 函式

soup.a.get_text(

)# 同soup.a.text

soup.find(

"a")

# 同soup.a

soup.find(

"a",屬性名=

"屬性值"

)# 根據屬性值定位到第乙個匹配到的標籤

注意: 若屬性名是 class 則需要在後面加個下劃線,寫成 class_

soup.findall(

"a")

# 獲取匹配到的所有標籤, 返回乙個列表

soup.findall(

["a"

,"b"])

# 可以獲取多種類的標籤

soup.findall(

"a", limit=2)

# 獲取前2個匹配到的標籤

soup.select(

"選擇器"

) 選擇器包括:

標籤選擇器:soup.select(

"a")

id選擇器:soup.select(

"#***"

) 類選擇器:soup.select(

".***"

) 層級選擇器:soup.select(

"div a"

)# 任意多級

或是:soup.select(

"div > a"

)# 直系的一級

注意:select函式返回的永遠是乙個列表

以上就是bs4的基本使用,歡迎指正

python爬蟲資料解析之bs4

步驟 1 匯入bs4庫 from bs4 import beautifulsoup2 獲取soup物件 html為你獲取的網頁源 將html轉化為特定的格式lxml 為後面提取資訊做準備 soup beautifulsoup html,lxml 3 利用方法選擇器解析 find all 查詢所有符合...

爬蟲架構 bs4

方便解析html xml等格式的原始碼,快速查詢 修改等操作,節省數小時乃至更多的工作時間 官網文件 from bs4 import beautifulsoup print path beautifulsoup path 非真實網頁 html doc 夏日炎炎,要你幹嘛 print soup.hea...

爬蟲 bs4模組

安裝 pip3 install beautifulsoup4 解析html和xml,修改html和xmlimport requests from bs4 import beautifulsoup 文件容錯能力,不是乙個標準的html也能解析 soup beautifulsoup html doc,l...