不能通过Python中的web抓取来获取产品的价格

2024-10-03 15:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在学习网络刮板,所以我决定练习一下。 使用这个网站(https://lista.mercadolivre.com.br/razer?matt_tool=6263806&matt_word=RAZER_MERCADO_LIVRE&gclid=CjwKCAiAs8XiBRAGEiwAFyQ-ejETB12X8G75icDJLMkW4ChSyBsJLrL3wZv_o3oZb8zvtUsc5D1tZBoCsNEQAvD_BwE),我想我应该在第一页收集每种产品的描述和价格。我可以很好地得到描述,但我有一个价格问题。在

例如,给定第一个产品,价格是559。但是,当我使用produto1.div.span.text时,Python只给我“R$”,这是我不想要的。 我该怎么做才能得到实际价格?在

我的代码:

url = 'https://lista.mercadolivre.com.br/razer?matt_tool=6263806&matt_word=RAZER_MERCADO_LIVRE&gclid=CjwKCAiAs8XiBRAGEiwAFyQ-ejETB12X8G75icDJLMkW4ChSyBsJLrL3wZv_o3oZb8zvtUsc5D1tZBoCsNEQAvD_BwE'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
produtos = html_soup.find_all('div', class_ = "item__info item__info--with-reviews")

produto1 = produtos[0]
produto1.div.span.text

Tags: texthttpsbrdivcomhtml价格matt
2条回答

<div>对象中有10个span标记。您只是获取第一个<span>标记。在

您可以通过以下操作获得下一个标签:

produto1.div.span.find_next('span').text

您可以通过查找所有<span>标记来查看它,然后遍历它:

^{pr2}$

输出:

Element: 0 Text: R$
Element: 1 Text: 559
Element: 2 Text: 12x   R$ 53 43
Element: 3 Text: 12x
Element: 4 Text: R$ 53 43
Element: 5 Text: 
Element: 6 Text: Razer Combo Holiday - Cynosa+goliathus+deathadder+kraken
Element: 7 Text: por Razer
Element: 8 Text: por Razer
Element: 9 Text: por Razer

你有很多选择

a)如果你只需要价格,你就可以瞄准价格。在

produtos = html_soup.find_all('span', class_ = "price__fraction")
print([item.text for item in produtos])

输出:

^{pr2}$

b)如果你只想得到价格,但想选择div以后再得到更多的项目,那也可以。在

produtos = html_soup.find_all('div', class_ = "item__info item__info with-reviews")
produto1 = produtos[0]
print(produto1.find('span',class_='price__fraction').text)

输出:

559

一旦您选择了产品div,从中获取数据只是使用BeautifulSoup进行正确选择的问题。您可以在文档的Searching the tree部分阅读更多内容。我将演示如何使用类和标记名过滤一些项。在

enter image description here

from requests import get
from bs4 import BeautifulSoup
url = 'https://lista.mercadolivre.com.br/razer?matt_tool=6263806&matt_word=RAZER_MERCADO_LIVRE&gclid=CjwKCAiAs8XiBRAGEiwAFyQ-ejETB12X8G75icDJLMkW4ChSyBsJLrL3wZv_o3oZb8zvtUsc5D1tZBoCsNEQAvD_BwE'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
produtos = html_soup.find_all('div', class_ = "item__info item__info with-reviews")
produto1 = produtos[0]
#price symbol
print(produto1.find('span',class_='price__symbol').text)
#price fraction / price
print(produto1.find('span',class_='price__fraction').text)
#main title
print(produto1.find('span','main-title').text.strip())

输出:

R$
559
Razer Combo Holiday - Cynosa+goliathus+deathadder+kraken

相关问题 更多 >