python - 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
解决方案
推荐阅读
- javascript - 如何为 mocha-webpack 分离文件
- c# - 从 json 字符串中提取信息并将其添加到 C# 中的列表中
- android - Flutter 项目超过 .dex 方法引用计数限制
- javascript - 根据数组中字符串值的索引对对象数组进行排序
- sqoop - 带有 sqoop 的 HANA 上的小写表名
- javascript - 带有可点击链接的标签,里面带有标签
- python - Python:FancyURLopener 在第二个循环中失败,ValueError:读取关闭的文件
- html - 如果变量为空,如何隐藏 DIV
- javascript - 如何测试返回带参数的函数的函数?
- javascript - D3 从下拉菜单中选择值以更新图表