首页 > 解决方案 > eBay 价格刮板 - 找到特定字符串或 div 类后停止刮板

问题描述

我正在尝试使用输入的一组关键字为自己组装一个基本的价格刮板并将它们加载到 eBay 搜索中。我意识到 eBay 有一个可能更适合这项工作的 API,但现在我只是想学习网络抓取的原理。

我目前让它运行得很好,但它在某些类型的搜索结果页面上返回不正确的结果,其中 eBay 添加了仅匹配某些关键字的结果。在这些页面上,有一个带有文本字符串的 div 元素将完全匹配的搜索结果和部分匹配的搜索结果(示例链接)分开: 示例图像

是否有一些代码可以添加到漂亮的汤或另一个库中,一旦找到某个 div 类或文本字符串就会停止抓取?我不希望刮板从该 div 之后返回任何值。

这是我目前拥有的,它从页面中提取所有价格值:

import requests, bs4, statistics as stat
from decimal import Decimal
from re import sub

kw = input('Enter an eBay search: ')
kw_norm = kw.replace(' ','+')

#  example url = https://www.ebay.com/sch/i.html?_from=R40&_nkw=1909-s+saint+gaudens+double+eagle&_sacat=0&rt=nc&LH_PrefLoc=1&_ipg=200

url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + kw_norm + '&_sacat=0&rt=nc&LH_PrefLoc=1&_ipg=200'
print(url)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')

prices = []
for price in soup.find_all('span', {'class': 's-item__price'}):
    new = price.text
    value = float((sub(r'[^\d.]', '', new)))
    prices.append(value)

# cropped code that returns min, max, mean, etc

标签: pythonweb-scraping

解决方案


推荐阅读