簡體   English   中英

Beautiful Soup 查找返回 [] 或無

[英]Beautiful Soup find returns [] or none

我正在制作我的第一個小 web 抓取程序。 我正在嘗試獲取產品的價格,但 soup.find 返回“無”。

import requests
from bs4 import BeautifulSoup

site = 'https://www.pichau.com.br/placa-de-video-asus-geforce-gtx-1650-dual-4gb-gddr5-128-bit-dual-gtx1650-4g'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.50'}

page = requests.get(site, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
price = soup.find(class_ = 'jss237')

print(price)

這是返回無,但是,如果我得到覆蓋整個東西的盒子的 class,就像這樣

price = soup.find(class_ = 'MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12 MuiGrid-grid-sm-5').get_text()

它返回所有內容,包括我想要獲得的價格

Placa de Video Asus GeForce GTX 1650 Dual, 4GB, GDDR5, 128-bit, DUAL-GTX1650-4G...SKU: DUAL-GTX1650-4Gà vistaR$1.989,00no PIX com 12% descontoR$ 2.260,23em até 12x de 188,35sem juros no cartão CaracterísticasGarantia: 12 Meses

.jsN class 名稱似乎是自動生成的,或者受 A/B 頁面的影響,所以我注意到在發布我的初始答案后它們會從加載變為加載(如果您想查看舊解決方案,請參閱編輯歷史記錄)。

主要價格在 static 標記中作為元數據提供:

<meta property="product:price:amount" content="R$1.989,00" />

Select 那與

print(soup.select_one('[property="product:price:amount"]')['content'])

如果你想要188,35 ,你可以使用一些附近的預期文本、圖標或 DOM 結構來識別它,或者在正文上使用正則表達式來獲取看起來價格的子字符串:

import re
import requests
from bs4 import BeautifulSoup

url = "https://www.pichau.com.br/placa-de-video-asus-geforce-gtx-1650-dual-4gb-gddr5-128-bit-dual-gtx1650-4g"
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.content, "lxml")
body = soup.select_one("body").decode_contents()
print(re.findall(r"\b(?:\d+\.)?\d+,\d{2,}\b", body)) 
# => ['1.989,00', '2.260,23', '188,35']

您可以比body更具體以減少誤報,但有可能依賴於現有的選擇器(取決於用例)。

請注意,我使用了 lxml,它比 html.parser 更快且更具適應性,但如果您手邊沒有 lxml,您可以使用 html.parser。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM