【问题标题】:Beautiful Soup find returns [] or noneBeautiful Soup 查找返回 [] 或无
【发布时间】:2022-01-18 21:55:26
【问题描述】:

我正在制作我的第一个小型网络抓取程序。我正在尝试获取产品的价格,但 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)

但是,如果我得到覆盖整个事物的盒子的类,这将返回 None,就像这样

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

【问题讨论】:

  • 您的预期输出/目标是什么?您只希望退回价格吗?

标签: python web-scraping beautifulsoup


【解决方案1】:

.jsN 类名似乎是自动生成的,或者受 A/B 页面的影响,所以我注意到在发布我的初始答案后它们正在从加载变为加载(如果您想查看,请参阅 edit history旧的解决方案)。

主要价格在静态标记中作为元数据提供:

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

选择那个

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多