所以我在為我正在開發的網站制作的網路抓取工具方面遇到了問題。我遇到的主要問題是,當嘗試為 h1 格式的產品獲取標題時,它不斷回應:
<h1 >CHERRY MX SILENT RED(10pcs)</h1>
我只想要 Cherry Mx Silent Red 部分而不是所有其他東西。這是我的網頁抓取工具的代碼:
from bs4 import BeautifulSoup
URL = 'https://kbdfans.com/collections/cherry-switches/products/cherry-mx-silent-red'
headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find('h1', {'class' : 'product-detail__title small-title'})
print(title)
uj5u.com熱心網友回復:
嘗試這個 :
title.get_text()
你的標題不是一個字串,它是一個物件
來自 BeautifulSoup 檔案:
The find_all() method looks through a tag’s descendants and retrieves all descendants that match your filters.
對于你的標題變數,你可以參考 bs4.element.Tag 檔案,如果你有疑問,你可以像這樣列印該物件的所有可用方法:
print(dir(title))
uj5u.com熱心網友回復:
從您<h1>剛剛使用的文本中獲取文本,.text以及.get_text()何時需要將自定義引數傳遞給strip空格,...或添加分隔符(例如title.get_text(strip=True, seperator=','))。
print(title.text)
或者
print(title.get_text())
例子
from bs4 import BeautifulSoup
URL = 'https://kbdfans.com/collections/cherry-switches/products/cherry-mx-silent-red'
headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
title = soup.find('h1', {'class' : 'product-detail__title small-title'})
print(title.text)
輸出
CHERRY MX SILENT RED(10pcs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344503.html
