如何用Python+BeautifulSoup判断Ebay已售商品是否接受最优报价?
解决Ebay已售商品是否接受最优报价的爬取问题
换个思路:放弃固定类名,找更稳定的判断标识
别死磕STRIKETHROUGH POSITIVE这个类了,Ebay页面的类名经常迭代调整,试试这几个更靠谱的方向:
直接搜索"Best Offer"相关文本:已售商品里,接受最优报价的通常会标注
Sold with Best Offer这类文字,直接在商品卡片范围内查找这个文本片段:# BeautifulSoup实现示例 is_best_offer = bool(item_card.find(string=lambda text: text and "Sold with Best Offer" in text))检查价格区域的特殊标记:部分商品的价格模块会带有
best-offer相关的data属性或徽章元素,比如:# 查找带best-offer标识的元素 best_offer_elem = item_card.select_one('[data-testid*="best-offer"], .best-offer-badge') is_best_offer = best_offer_elem is not None
优化Selenium的动态加载处理
如果用Selenium还是拿不到目标元素,大概率是等待逻辑没写对——别用固定sleep,改用显式等待定位商品容器,再在容器内查找:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待商品卡片全部加载完成(假设商品卡片类名为s-item__wrapper) wait = WebDriverWait(driver, 10) item_cards = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, "s-item__wrapper"))) for card in item_cards: # 方式1:检查卡片内是否有Sold with Best Offer文本 is_best_offer = "Sold with Best Offer" in card.text # 方式2:查找删除线价格(用页面实际的类名,比如现在Ebay常用strikethrough-text) strikethrough_elem = card.find_element(By.CSS_SELECTOR, "span.strikethrough-text") is_best_offer = strikethrough_elem is not None
先确认页面真实结构
打开Ebay已售商品页面,用浏览器开发者工具的Elements面板(别用实时选择器,动态元素可能消失),搜索"Best Offer"相关元素,看当前页面实际用的类名、属性是什么——比如现在很多商品的删除线价格用的是strikethrough-text类,不是你之前找的那个。
集成到你的Flask API示例
把判断逻辑套进现有爬取流程里:
from flask import Flask, request, jsonify from bs4 import BeautifulSoup import requests app = Flask(__name__) @app.route('/scrape-ebay-sold', methods=['GET']) def scrape_ebay(): search_query = request.args.get('q') url = f"https://www.ebay.com/sch/i.html?_nkw={search_query}&LH_Sold=1" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') items = soup.select('.s-item__wrapper') results = [] for item in items: title = item.select_one('.s-item__title').text.strip() price = item.select_one('.s-item__price').text.strip() sold_date = item.select_one('.s-item__soldDate').text.strip() # 判断是否接受最优报价 is_best_offer = bool(item.find(string=lambda t: t and "Sold with Best Offer" in t)) results.append({ "title": title, "price": price, "sold_date": sold_date, "accepts_best_offer": is_best_offer }) return jsonify(results) if __name__ == '__main__': app.run(debug=True)
内容的提问来源于stack exchange,提问作者bunkered_reageant
相关产品推荐
相关产品推荐

