在python中使用BS4创建stockchecker



我使用webdriver打开这个链接https://www.alternate.be/Grafische-kaarten?s=default& pr1 = 0, pr2 = 6655, filter_2203 = NVIDIA GeForce + + RTX + 3060 + Ti。

然后搜索标签"Op voorraad"在page_source,但我没有找到它。我怎样才能找到正确的元素?

此站点使用客户端呈现。在使用beautifulsoup之前使用selenium之类的东西来填充信息

您可以使用BeautifulSoup网页抓取库抓取此网站,而无需使用selenium,它将比启动整个浏览器快得多。

要获得所需的数据,您需要获得包含我们需要的数据的.class选择器'。如果这样更有意义的话,可以把容器想象成俄罗斯套娃。

换句话说,我们需要找到一个CSS选择器,其中有关于价格,可用性和标题的数据,在我们的情况下,它是.boxCounter选择器。

要轻松找到选择器,您可以使用SelectorGadget Chrome扩展,允许您通过单击浏览器中所需的元素并返回它来选择选择器。如果页面大量使用JS,它并不总是工作完美(在这种情况下,它工作正常)。

使用Beautifulsoup检查在线IDE中的代码。

from bs4 import BeautifulSoup
import requests, json, lxml
html = requests.get("https://www.alternate.be/Grafische-kaarten?s=default&pr1=0&pr2=6655&filter_2203=NVIDIA+GeForce+RTX+3060+Ti", timeout=30)
soup = BeautifulSoup(html.text, "lxml") 
data = []
# iterating over every container (listing) and extracting data from individual listing
for result in soup.select(".boxCounter"):
availability = result.select_one(".text-right .font-weight-bold").text
price = result.select_one(".price").text
title = result.select_one("#listing .font-weight-bold").text
data.append({
"availability" : availability,
"price" : price,
"title" : title
})
print(json.dumps(data, indent=2, ensure_ascii=False))

示例输出

[
{
"availability": "Op voorraad",
"price": "€ 599,00",
"title": "GIGABYTE AORUSGeForce RTX 3060 Ti ELITE grafische kaart"
},
{
"availability": "Op voorraad",
"price": "€ 539,00",
"title": "MSIGeForce RTX 3060 Ti VENTUS 2X 8G V1 grafische kaart"
},
{
"availability": "Op voorraad",
"price": "€ 549,00",
"title": "GIGABYTEGeForce RTX 3060 Ti Eagle OC 8G grafische kaart"
},
{
"availability": "Op voorraad",
"price": "€ 569,00",
"title": "GIGABYTEGeForce RTX 3060 Ti VISION OC 8G grafische kaart"
},
{
"availability": "Op voorraad",
"price": "€ 649,00",
"title": "MSIGeForce RTX 3060 Ti GAMING Z TRIO grafische kaart"
},
{
"availability": "Niet op voorraad, geen informatie beschikbaar",
"price": "€ 599,00",
"title": "ASUSGeForce RTX 3060 Ti TUF GAMING OC V2 grafische kaart"
},
# ...
]

最新更新