You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用BeautifulSoup爬取eBay数据时如何按关键词过滤结果

实现关键词过滤的修改方案

你只需要在获取到标题后增加关键词匹配逻辑即可,调整后的完整代码如下:

from bs4 import BeautifulSoup
import requests

url ='https://www.ebay.fr/sch/267/i.html?_from=R40&_nkw=star+wars&_sop=10&_ipg=200'

def get_data(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    return soup

def parse(soup):
    results = soup.find_all('div', {'class' : 's-item__info clearfix'})
    # 把data列表挪到循环外,避免每次遍历都重置
    data = []
    # 定义过滤关键词
    filter_keyword = 'Thrawn'
    for item in results:
        try:
            Title = item.find('h3', {'class': 's-item__title'}).text.replace('Nouvelle annonce','')
            # 新增关键词判断,可根据需求选择是否区分大小写
            # 区分大小写的写法
            if filter_keyword not in Title:
                continue
            # 不区分大小写的写法(二选一即可)
            # if filter_keyword.lower() not in Title.lower():
            #     continue
            Price = item.find('span', {'class':'s-item__price'}).text
            Link = item.find('a', {'class' : 's-item__link'})['href']

            products = {'Title' : Title, 'Price' : Price, 'Link' : Link}
            data.append(products)
            print(products)

        except:
            continue
    return data
soup = get_data(url)
filtered_data = parse(soup)

修改说明

  • 原代码中data列表定义在for循环内部,每次遍历都会被清空重置,调整到循环外部后可以存储所有符合条件的结果
  • 新增关键词匹配判断:不满足匹配条件的条目直接跳过后续处理,仅保留标题含指定关键词的条目
  • 提供了区分大小写和不区分大小写两种匹配规则,可根据实际需求选择使用

运行调整后的代码,只会打印标题包含Thrawn的条目,和你需要的效果一致。

内容的提问来源于stack exchange,提问作者Oxykore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:45:07