教程

如何用Python抓取eBay数据:API、商品列表、CSV与代理配置

了解如何用Python通过获准API抓取eBay商品数据,处理分页、去重、价格与运费校验,并在授权场景下检查SOCKS5代理出口。

Gideon ReedGideon Reed25 分钟阅读

本文介绍如何在获准使用eBay数据源的前提下,用Python完成商品搜索、分页、去重、价格与运费校验以及CSV导出。文中同时演示授权HTML解析和可选的SOCKS5出口检查。代理只提供网络连接,不能代替eBay的API资格、平台许可或目标数据的使用授权。

先看结论: 先运行本地自测,再运行演示模式生成CSV和带日期的日志。只有在获得批准的生产应用中,才切换到live模式。代理只提供网络连接,不能代替eBay的API授权或自动化采集许可。

在本地fixture运行中,两页、四条模拟记录最终产生三条唯一记录和一条重复记录;其中一条记录通过数值校验,两条记录进入复核流程。该结果来自本地样本,不代表实时eBay数据。

execution-results

1.先确定数据来源,再编写抓取程序

eBay的用户协议对自动化访问设有许可要求,Browse API还适用独立的应用资格、配额和使用条件。公开页面可见性、代理连接和自动化采集授权不能相互替代。

数据来源 适用范围 配置与运行取舍
获准使用的Browse API 结构化获取当前报价和支持的详情字段 需要应用权限、OAuth、配额和Schema处理
获授权保存的HTML 解析许可抓取文件中实际存在的字段 需要维护选择器并保存原始采集背景
受维护的数据服务 获取合同约定的字段和时效 需要核对来源、范围、验证成本和交付条款
代理连接 为授权流程提供配置好的网络出口 需要检查连接、地区和会话;代理本身不是数据集

用于价格监测时,应该选择哪种eBay数据来源?

如果需要的字段和配送上下文能够由结构化、获准的数据源提供,优先使用该来源。Browse API搜索参考说明了q、limit、offset以及商品摘要字段。单页最多可请求200条,一个结果集最多10000条。本文程序主动限制为三页,不尝试耗尽整个目录。

数据需求 搜索摘要 商品详情或其他获准来源
标题、商品ID、显示价格 提取接口返回的支持字段 仅在必要时请求更多详情
成色和卖家业务标识 保留可用字段及缺失标记 通过获准方法补充报价详情
精确商品变体 保存返回的商品/变体身份 摘要字段不能证明所有变体都已枚举
运费与配送条款 提供目的地上下文;复核缺失或含糊选项 确认适用报价和目的地
已售商品、实际收入或评价历史 不能从挂牌价或当前竞价推断 需要独立且适用的数据源

2.安装并准备应用

**实时访问需要开发者凭据和生产环境资格;Sandbox与Production是两套不同环境。**请先确认应用符合Buy API生产环境要求,再按照eBay OAuth客户端凭据流程获取应用令牌。

WindowsPowerShell安装:

powershellpowershell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install "requests[socks]" beautifulsoup4

如果系统没有PythonLauncher,但python --version显示的是目标Python3,可用python -m venv .venv创建环境。之后继续使用虚拟环境中的明确解释器。

macOS或Linux安装:

bashbash
python3 -m venv .venv
.venv/bin/python -m pip install 'requests[socks]' beautifulsoup4

将第4节的完整程序保存为ebay_browse.py。实时运行需要以下环境变量:

变量 含义
EBAY_CLIENT_ID 获准生产应用的客户端ID
EBAY_CLIENT_SECRET 客户端密钥,应通过本地密钥管理流程提供
EBAY_PROXY_URL 可选的已生成代理URL;直连API时省略
IPINFO_TOKEN 仅用于代理出口检查的IPinfo Lite查询令牌

程序使用client-credentials获取令牌,并只在内存中保存。令牌和密钥不会写入CSV或日志。OAuth凭据交换使用独立的HTTPS直连会话;可选代理只用于研究会话。

3.四个核心操作:请求、解析、校验和导出

稳定的eBay数据流程应把请求参数、页面时间、金额校验和去重策略一起保存。 下面是完整程序前的关键片段。

请求

实时分支会发送查询词、页大小、偏移量、市场和配送目的地标头。

pythonpython
params = dict(q=args.query, limit=args.limit, offset=offset)
headers = {
    'Authorization': 'Bearer ' + access,
    'X-EBAY-C-MARKETPLACE-ID': args.marketplace,
    'X-EBAY-C-ENDUSERCTX': 'contextualLocation=' + quote(
        f'country={args.country},zip={args.postal}', safe=''),
}

解析

每取得一页数据后再记录时间,不要在所有请求开始前只记录一个统一时间。

pythonpython
observed = now()
items = payload.get('itemSummaries', [])
row = normalize(item, context)

校验

金额使用Decimal处理。拍卖、缺失运费和货币冲突的记录不进入可直接比较的数值集合。

pythonpython
pv, sv = amount(price.get('value')), amount(shipping.get('value'))
subtotal = pv + sv if not reasons else None

导出

同一商品/变体第一次成功出现时保留其原始页面和时间戳,并创建新的CSV,不覆盖此前运行结果。

pythonpython
key = (row['item_id'], row['variation_id'])
if key in seen:
    duplicates += 1
    continue

实时循环会在没有next、商品列表为空、出现错误或达到页数上限时停止。程序自行计算下一个offset,不盲目跟随返回URL。搜索分页不是事务一致性快照,因此去重不能证明已经覆盖全部符合条件的报价。

4.API到CSV的完整Python程序

演示模式使用脚本内的本地JSON样式记录;live模式才会获取应用令牌并调用Browse搜索。 不要把输出文件名设为需要保留的已有文件。

pythonpython
import argparse, csv, ipaddress, json, os, sys
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path
from urllib.parse import quote, urlsplit
import requests

BASE = 'https://api.ebay.com'
SEARCH = BASE + '/buy/browse/v1/item_summary/search'

class Stop(Exception):
    pass

def now():
    return datetime.now(timezone.utc).isoformat()

def amount(value):
    try:
        n = Decimal(str(value))
        return n if n.is_finite() and n >= 0 else None
    except (InvalidOperation, ValueError):
        return None

def normalize(item, context):
    price = item.get('price') or item.get('currentBidPrice') or {}
    options = item.get('shippingOptions') or []
    shipping = options[0].get('shippingCost', {}) if len(options) == 1 else {}
    pv, sv = amount(price.get('value')), amount(shipping.get('value'))
    currency = price.get('currency', '')
    modes = item.get('buyingOptions') or []
    mode = 'auction' if 'AUCTION' in modes else 'fixed_price' if 'FIXED_PRICE' in modes else 'unknown'
    ident = str(item.get('itemId', ''))
    parts = ident.split('|')
    variation = parts[2] if len(parts) == 3 and parts[2] != '0' else ''
    reasons = []
    for name, good in [('item_id', ident), ('title', item.get('title')),
            ('condition', item.get('conditionId')), ('price', pv is not None),
            ('shipping', sv is not None), ('fixed_price', mode == 'fixed_price'),
            ('currency', currency == context['expected_currency']),
            ('shipping_currency', bool(currency) and shipping.get('currency') == currency)]:
        if not good:
            reasons.append(name)
    subtotal = pv + sv if not reasons else None
    return dict(item_id=ident, variation_id=variation, title=item.get('title', ''),
        price_raw=str(price.get('value', '')), price_amount=str(pv) if pv is not None else '',
        currency=currency, shipping_raw=str(shipping.get('value', '')),
        shipping_amount=str(sv) if sv is not None else '',
        condition=item.get('condition', ''), condition_id=item.get('conditionId', ''),
        buying_format=mode, seller=(item.get('seller') or {}).get('username', ''),
        item_url=item.get('itemWebUrl', ''), price_plus_shipping=str(subtotal) if subtotal is not None else '',
        numeric_ready=not reasons, review_reason=';'.join(reasons), **context)

def sample_pages():
    def item(number, value, currency='USD', auction=False, ship=True):
        row = dict(itemId=f'v1|11000000000{number}|0', title=f'Fixture camera offer {number}',
            price=dict(value=value, currency=currency), condition='Used', conditionId='3000',
            buyingOptions=['AUCTION'] if auction else ['FIXED_PRICE'],
            seller=dict(username='fixture-seller'), itemWebUrl=f'https://www.ebay.com/itm/11000000000{number}')
        if ship:
            row['shippingOptions'] = [dict(shippingCost=dict(value='8.00', currency='USD'))]
        return row
    first = item(1, '120.00')
    return [dict(itemSummaries=[first, item(2, '75.00', auction=True, ship=False)], next='fixture-page-2'),
            dict(itemSummaries=[dict(first, price=dict(value='121.00', currency='USD')), item(3, '90.00', currency='EUR')])]

def response_json(response):
    if response.status_code != 200:
        raise Stop(f'HTTP_{response.status_code}: stop; inspect authorization, access or quota')
    if 'json' not in response.headers.get('Content-Type', '').lower():
        raise Stop('MIME: expected JSON')
    try:
        data = response.json()
    except ValueError:
        raise Stop('JSON: response cannot be decoded as JSON') from None
    if not isinstance(data, dict):
        raise Stop('SCHEMA: expected a JSON object')
    if data.get('errors'):
        raise Stop('API_ERRORS: review the approved request and API diagnostics')
    return data

def session():
    s = requests.Session()
    s.trust_env = False
    return s

def token():
    key, secret = os.environ.get('EBAY_CLIENT_ID'), os.environ.get('EBAY_CLIENT_SECRET')
    if not key or not secret:
        raise Stop('CREDENTIALS: set the approved production application credentials locally')
    with session() as auth:
        with auth.post(BASE + '/identity/v1/oauth2/token', auth=(key, secret),
                data=dict(grant_type='client_credentials', scope='https://api.ebay.com/oauth/api_scope'),
                timeout=(10, 30), allow_redirects=False) as response:
            value = response_json(response).get('access_token')
    if not value:
        raise Stop('TOKEN: response has no access_token')
    return value

def route_check(client, expected):
    check_token = os.environ.get('IPINFO_TOKEN')
    if not check_token:
        raise Stop('IP_CHECK: set an IPinfo Lite token for the requested route check')
    with client.get('https://api.ipinfo.io/lite/me',
            headers={'Authorization': 'Bearer ' + check_token},
            timeout=(10, 30), allow_redirects=False) as response:
        data = response_json(response)
    country = data.get('country_code', '')
    ip = ipaddress.ip_address(data.get('ip', ''))
    masked = str(ipaddress.ip_network(f'{ip}/' + ('24' if ip.version == 4 else '48'), strict=False))
    if expected and country != expected:
        raise Stop('EXIT_COUNTRY: result does not match the requested exit country')
    return dict(observed_utc=now(), ip_network_redacted=masked, country=country,
        asn=data.get('asn', ''), as_name=data.get('as_name', ''), source='IPinfo Lite')

def collect(args):
    fixture = sample_pages() if args.demo else None
    proxy = os.environ.get('EBAY_PROXY_URL')
    if args.demo and proxy:
        raise Stop('LOCAL_INPUT: clear EBAY_PROXY_URL before an offline run')
    records, seen, duplicates, pages = [], set(), 0, 0
    routes = []
    with session() as client:
        access = ''
        if args.live:
            if proxy:
                parsed = urlsplit(proxy)
                if parsed.scheme not in {'socks5h', 'http', 'https'} or not parsed.hostname or not parsed.port:
                    raise Stop('PROXY_CONFIG: use a supported generated endpoint')
                client.proxies.update({'http': proxy, 'https': proxy})
                routes.append(dict(route='configured_proxy', **route_check(client, args.expected_exit)))
                if args.direct_baseline:
                    with session() as direct:
                        routes.append(dict(route='direct_baseline', **route_check(direct, '')))
            elif args.direct_baseline:
                raise Stop('BASELINE: a proxy route is required for the comparison')
            access = token()
        for page in range(1, args.pages + 1):
            offset = (page - 1) * args.limit
            params = dict(q=args.query, limit=args.limit, offset=offset)
            source_url = requests.Request('GET', SEARCH, params=params).prepare().url
            if fixture is not None:
                if page > len(fixture):
                    break
                payload = fixture[page - 1]
                source_url = f'fixture://browse/page/{page}'
            else:
                headers = {'Authorization': 'Bearer ' + access,
                    'X-EBAY-C-MARKETPLACE-ID': args.marketplace,
                    'X-EBAY-C-ENDUSERCTX': 'contextualLocation=' + quote(f'country={args.country},zip={args.postal}', safe='')}
                with client.get(SEARCH, params=params, headers=headers,
                        timeout=(10, 30), allow_redirects=False) as response:
                    payload = response_json(response)
                    source_url = response.url
            observed = now()  # after this page's response/fixture has been obtained
            if not isinstance(payload.get('itemSummaries', []), list):
                raise Stop('SCHEMA: itemSummaries must be a list')
            items = payload.get('itemSummaries', [])
            pages += 1
            if not items:
                break
            context = dict(observed_utc=observed, page=page, offset=offset,
                source_url=source_url, query=args.query, marketplace=args.marketplace,
                delivery_country=args.country, delivery_postal=args.postal,
                expected_currency=args.currency, tax_basis='excluded_from_subtotal',
                sample_type='local_api_fixture' if args.demo else 'browse_api_response')
            for item in items:
                if not isinstance(item, dict) or not item.get('itemId'):
                    raise Stop('SCHEMA: every record needs itemId')
                row = normalize(item, context)
                key = (row['item_id'], row['variation_id'])
                if key in seen:
                    duplicates += 1
                    continue  # first successful observation wins; its timestamp stays unchanged
                seen.add(key)
                records.append(row)
            if not payload.get('next'):
                break
    if not records:
        raise Stop('EMPTY: no listing records; no CSV written')
    return records, dict(pages=pages, duplicates_skipped=duplicates, routes=routes)

def self_test():
    from types import SimpleNamespace
    from unittest.mock import patch
    c = dict(expected_currency='USD')
    a, b = sample_pages()[0]['itemSummaries']
    checks = [normalize(a, c)['price_plus_shipping'] == '128.00',
        not normalize(b, c)['numeric_ready'], amount('NaN') is None,
        amount('-1') is None, amount('120 to 130') is None,
        normalize(sample_pages()[1]['itemSummaries'][1], c)['numeric_ready'] is False,
        normalize(dict(a, conditionId=''), c)['numeric_ready'] is False,
        normalize(dict(a, itemId='v1|110000000001|7'), c)['variation_id'] == '7']
    args = SimpleNamespace(demo=True, live=False, pages=2, limit=2, query='camera body',
        marketplace='EBAY_US', country='US', postal='10001', currency='USD')
    with patch(__name__ + '.now', side_effect=['2026-11-12T00:00:01+00:00', '2026-11-12T00:00:02+00:00']):
        rows, report = collect(args)
    checks.extend([len(rows) == 3, report['duplicates_skipped'] == 1, report['pages'] == 2,
        rows[0]['price_amount'] == '120.00', rows[2]['page'] == 2,
        rows[0]['source_url'] == 'fixture://browse/page/1',
        len({r['observed_utc'] for r in rows}) == 2,
        all(r['tax_basis'] == 'excluded_from_subtotal' for r in rows)])
    if not all(checks):
        raise Stop('SELF_TEST: a normalization check failed')
    print(f'Local normalization and pagination checks: {len(checks)} passed')

def main():
    p = argparse.ArgumentParser()
    modes = p.add_mutually_exclusive_group(required=True)
    modes.add_argument('--demo', action='store_true')
    modes.add_argument('--live', action='store_true')
    modes.add_argument('--self-test', action='store_true')
    p.add_argument('--query', default='camera body')
    p.add_argument('--pages', type=int, choices=range(1, 4), default=2)
    p.add_argument('--limit', type=int, choices=range(1, 201), default=2)
    p.add_argument('--marketplace', default='EBAY_US')
    p.add_argument('--country', default='US')
    p.add_argument('--postal', default='10001')
    p.add_argument('--currency', default='USD')
    p.add_argument('--expected-exit', default='US')
    p.add_argument('--direct-baseline', action='store_true')
    p.add_argument('--out', type=Path, default=Path('ebay-api.csv'))
    args = p.parse_args()
    if args.self_test:
        self_test()
        return
    run_file = args.out.with_suffix('.run.json')
    if args.out.exists() or run_file.exists():
        raise Stop('OUTPUT_EXISTS: choose a new output name')
    rows, report = collect(args)
    def safe(v):
        s = str(v)
        return "'" + s if s.lstrip().startswith(('=', '+', '-', '@')) else s
    with args.out.open('x', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows({k: safe(v) for k, v in row.items()} for row in rows)
    report.update(run_utc=now(), rows=len(rows), numeric_ready=sum(r['numeric_ready'] for r in rows),
        sample_type=rows[0]['sample_type'], dedup_policy='first_successful_observation')
    with run_file.open('x', encoding='utf-8') as f:
        json.dump(report, f, indent=2)
    print(f'Pages: {report["pages"]}; unique rows: {len(rows)}; duplicates skipped: {report["duplicates_skipped"]}')
    print(f'Numeric-ready: {report["numeric_ready"]}; review: {len(rows) - report["numeric_ready"]}')
    print(f'CSV: {args.out.name}; log: {run_file.name}')

if __name__ == '__main__':
    try:
        main()
    except Stop as e:
        print(f'Stopped: {e}', file=sys.stderr)
        sys.exit(2)
    except requests.RequestException as e:
        label = 'PROXY' if isinstance(e, requests.exceptions.ProxyError) else 'TLS' if isinstance(e, requests.exceptions.SSLError) else 'TIMEOUT' if isinstance(e, requests.exceptions.Timeout) else 'DNS_OR_CONNECTION' if isinstance(e, requests.exceptions.ConnectionError) else 'NETWORK'
        print(f'Stopped: {label}; inspect the route without sharing credential-bearing exceptions', file=sys.stderr)
        sys.exit(2)
    except (ValueError, OSError, TypeError):
        print('Stopped: INPUT_OR_RESPONSE; check configuration, paths and response schema', file=sys.stderr)
        sys.exit(2)

5.运行程序并检查输出

先运行自测,再用演示模式生成本地CSV:

powershellpowershell
Remove-Item Env:EBAY_PROXY_URL -ErrorAction SilentlyContinue
.\.venv\Scripts\python.exe .\ebay_browse.py --self-test
.\.venv\Scripts\python.exe .\ebay_browse.py --demo --out api-fixture.csv

程序会输出类似以下结果:

texttext
Local normalization and pagination checks: 16 passed
Pages: 2; unique rows: 3; duplicates skipped: 1
Numeric-ready: 1; review: 2
CSV: api-fixture.csv; log: api-fixture.run.json
csv-results

CSV表头和两个输出记录

下面保留完整表头和前两条本地记录。时间戳来自执行记录,不是统一填入的运行开始时间。

csvcsv
item_id,variation_id,title,price_raw,price_amount,currency,shipping_raw,shipping_amount,condition,condition_id,buying_format,seller,item_url,price_plus_shipping,numeric_ready,review_reason,observed_utc,page,offset,source_url,query,marketplace,delivery_country,delivery_postal,expected_currency,tax_basis,sample_type
v1|110000000001|0,,Fixture camera offer 1,120.00,120.00,USD,8.00,8.00,Used,3000,fixed_price,fixture-seller,https://www.ebay.com/itm/110000000001,128.00,True,,2026-11-12T06:06:20.396005+00:00,1,0,fixture://browse/page/1,camera body,EBAY_US,US,10001,USD,excluded_from_subtotal,local_api_fixture
v1|110000000002|0,,Fixture camera offer 2,75.00,75.00,USD,,,Used,3000,auction,fixture-seller,https://www.ebay.com/itm/110000000002,,False,shipping;fixed_price;shipping_currency,2026-11-12T06:06:20.396005+00:00,1,0,fixture://browse/page/1,camera body,EBAY_US,US,10001,USD,excluded_from_subtotal,local_api_fixture

第一条记录的商品价格为USD120.00,运费为USD8.00,合计为税费和其他费用之前的USD128.00。numeric_ready=True只表示金额和必要字段通过了定义的校验,不代表它与其他商品完全等价,也不代表结账最终金额。

第二条记录是缺少运费的拍卖商品。第三条记录的价格为EUR,而运费为USD,与预期USD上下文冲突。两条记录都保留在输出中,并写入复核原因,避免被错误当成“最低到手价”。

quality-results

重复记录和时间戳是怎么处理的?

第二个fixture页面重复了第一条报价,但价格发生变化。程序采用第一次成功观测优先,因此保留第一页的价格和采集时间。如果业务采用最后一次观测优先,就必须替换完整观测记录,包括时间戳和来源,不能只改价格。

每个成功页面都有自己的observed_utc、来源URL、查询词、页码和offset。快速本地页面在某些系统上可能产生相同的时钟值;关键是每页分别记录,而不是人为制造不同时间。

provenance-results

执行获准的实时API请求

从本地密钥管理器读取EBAY_CLIENT_ID和EBAY_CLIENT_SECRET,再运行:

powershellpowershell
.\.venv\Scripts\python.exe .\ebay_browse.py --live --query "camera body" --limit 20 --pages 2 --marketplace EBAY_US --country US --postal 10001 --currency USD --out approved-api.csv

该命令请求EBAY_US市场、US配送目的地的商品列表。Browse配送上下文说明解释了contextualLocation标头。市场、商品所在地、配送目的地和代理出口是不同输入,不能互相推断。

.run.json文件会记录页数、跳过的重复数、可数值比较记录数、样本类型和执行过的路由检查。如果后续页面失败,程序会在CSV导出前停止,避免生成看似完整的部分数据。

6.把获授权保存的HTML作为第二条路径

只有在HTML文件本身属于获准来源时,才使用这条路径。 保留原始采集时间和来源URL。parsed_utc表示处理文件的时间,不是市场报价被观察到的时间。

使用选择器前先检查输入页面。下面的.s-item和.s-card只是兼容性模式,不是永久的eBay标记契约。程序会把每条HTML记录送入上下文复核,不会自行补写成色、货币或配送信息。

将下面的完整程序另存为ebay_html.py:

pythonpython
import argparse, csv, os, re
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urljoin, urlsplit, parse_qs, urlencode
from bs4 import BeautifulSoup

def main():
    p = argparse.ArgumentParser()
    p.add_argument('html', type=Path)
    p.add_argument('--captured-utc', required=True)
    p.add_argument('--source-url', required=True)
    p.add_argument('--out', type=Path, default=Path('ebay-html.csv'))
    args = p.parse_args()
    stamp = datetime.fromisoformat(args.captured_utc.replace('Z', '+00:00'))
    if stamp.utcoffset() is None:
        p.error('captured-utc must include a timezone')
    if os.environ.get('EBAY_PROXY_URL'):
        p.error('clear EBAY_PROXY_URL; this path parses local HTML only')
    if args.out.exists():
        p.error('choose a new output filename')
    soup = BeautifulSoup(args.html.read_text(encoding='utf-8'), 'html.parser')
    def text(card, selectors):
        n = card.select_one(selectors)
        return n.get_text(' ', strip=True) if n else ''
    rows, seen = [], set()
    for card in soup.select('.s-item, .s-card'):
        for link in card.select('a[href]'):
            u = urlsplit(urljoin('https://www.ebay.com', link['href']))
            match = re.search(r'/itm/(?:[^/?]+/)?(\d{9,15})(?:[/?#]|$)', u.path)
            if u.scheme != 'https' or u.hostname not in {'www.ebay.com', 'ebay.com'} or not match:
                continue
            item_id, variation = match[1], parse_qs(u.query).get('var', [''])[0]
            if (item_id, variation) in seen:
                break
            seen.add((item_id, variation))
            price = text(card, '.s-item__price, .s-card__price')
            shipping = text(card, '.s-item__shipping, .s-item__logisticsCost, .s-card__shipping')
            review = ['html_context_review']
            if not shipping:
                review.append('shipping_missing')
            if re.search(r'\s(?:to|[-–])\s', price):
                review.append('price_range')
            rows.append(dict(item_id=item_id, variation_id=variation,
                title=text(card, '.s-item__title, .s-card__title'), price_raw=price,
                shipping_raw=shipping, captured_utc=stamp.astimezone(timezone.utc).isoformat(),
                parsed_utc=datetime.now(timezone.utc).isoformat(), source_url=args.source_url,
                review_reason=';'.join(review)))
            break
    if not rows:
        p.error('no valid items: inspect the saved page and selectors')
    def safe(v):
        return "'" + v if v.lstrip().startswith(('=', '+', '-', '@')) else v
    with args.out.open('x', encoding='utf-8-sig', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0]))
        w.writeheader()
        w.writerows({k: safe(v) for k, v in r.items()} for r in rows)
    print(f'HTML rows: {len(rows)}; source capture time retained; all rows require context review')

if __name__ == '__main__':
    main()

对获授权的HTML文件,使用该文件实际的采集时间和来源:

powershellpowershell
.\.venv\Scripts\python.exe .\ebay_html.py .\authorized-search.html --captured-utc "2026-11-12T06:00:00Z" --source-url "https://www.ebay.com/sch/i.html?_nkw=camera&_pgn=1" --out saved-html.csv

本地三卡片fixture生成三条记录:一条看起来是固定价且带变体7,一条缺失运费,一条价格区间为USD90–100。价格区间会保留两个端点并标记price_range,不会被压缩成USD90报价。该次本地运行的来源URL为fixture://html/page/1。

ebay-reference

7.配置可选的Socks5.IO连接

只有在授权项目需要住宅网络出口时,才配置代理。 直连获准API可能已经满足需求。代理提供连接能力,不提供应用批准、缺失字段或自动采集权。

1.打开已购买的住宅代理产品,进入Proxy Setup。
2.选择代理子账号、目标出口市场、支持的协议和会话模式。网关/接入点与目标出口是两个概念。
3.复制生成的主机、端口、代理用户名和密码。它们不是控制台登录凭据。
4.根据实际流程选择会话连续性。住宅代理会话控制文档区分sticky和rotating模式。应使用当前产品生成的值,不要套用其他产品的用户名后缀或超时设置。

socks-subaccount

socks-proxy-setup
用本地保存的密钥创建变量;必要时对凭据组件进行URL编码:

powershellpowershell
$env:EBAY_PROXY_URL = 'socks5h://ENCODED_USER:ENCODED_PASSWORD@GENERATED_HOST:GENERATED_PORT'

这是模板,不是可直接使用的端点。Requests的SOCKS文档区分socks5h的代理端DNS解析和socks5的客户端DNS解析。选择的产品和客户端支持时,也可以使用HTTP(S);协议本身不能保证网站访问成功。

收集eBay数据前,如何验证SOCKS5代理的出口位置?

应在与获准Browse请求相同的Requests会话中检查出口。 程序使用IPinfo Lite查询接口,其国家和ASN响应独立于eBay市场或配送设置。先在本地设置IPINFO_TOKEN,再运行:

powershellpowershell
.\.venv\Scripts\python.exe .\ebay_browse.py --live --expected-exit US --direct-baseline --query "camera body" --limit 20 --pages 1 --country US --postal 10001 --out routed-api.csv

如果设置了EBAY_PROXY_URL,程序会先检查该会话,并在国家不匹配时停止。–direct-baseline会额外检查独立直连会话。程序记录UTC时间、国家、ASN和脱敏后的IP网段,不记录令牌或完整代理URL。两个会话都会关闭环境变量中的代理继承。两条JSON路由记录可以区分两条路径;相同的脱敏网段不能证明完整IP相同。

如果使用RoxyBrowser手动检查,应使用同一代理生成的协议和字段,再单独验证启动的浏览器Profile。浏览器检查不能证明Python进程使用了相同路由。

roxy-fields
故障 排查顺序 处理判断
407或代理认证错误 产品状态→生成的主机/端口→代理凭据→支持的协议 修正配置后再观察
DNS或连接失败 网关解析→路由可用性→端点/端口→代理端DNS支持 保留具体失败阶段,不暴露带凭据异常
TLS错误 证书信任和端点配置 不要关闭TLS验证
出口国家不符 同会话查询→所选市场→生成的用户名/会话设置 收集依赖地区的数据前停止
API401 令牌环境、过期时间和作用域 获取正确应用令牌,不设置自动凭据重试循环
API403 应用资格和获准用途 解决访问批准问题,不要轮换出口
API429 应用配额和适用时间表 停止并遵循服务限制
JSON无效、MIME错误或缺少itemId 响应格式和Schema 停止,避免导出误导性记录

8.把导出结果变成可辩护的报价比较

持续做价格监测时,应先定义比较组:型号/变体、成色、购买方式、货币、配送目的地和适用费用。numeric_ready只是算术和字段完整性检查,不代表同一查询下的所有记录都是等价商品。

比较字段 必须如何处理
item_id+variation_id 用于身份识别和重复控制
成色与型号/变体 只比较等价报价;对含糊变体进行复核
固定价与拍卖 当前竞价不能放进固定价排名
商品货币与运费货币 与预期货币匹配,不要静默换算
配送国家/邮编 保存实际请求值,不从IP地理位置推断
商品价格加运费 仅用支持的金额计算;税费不包含在该小计中
税费与结账条件 获取相关条款后,才能称为最终到手价小计
时间戳与来源 保存每页观测时间和首次出现的来源

本地受控样本中,一条记录可以直接做数值比较,一条缺少运费,另一条存在货币冲突。这是该样本的数据质量结果,不是eBay全站缺字段率或成功率。后续搜索中消失的商品,也不能被解释为已售出。

结论

要让eBay数据真正可用,需要完成从获取到校验的完整闭环:使用获准应用认证,保留页面和配送上下文,分离不完整报价,并导出可追溯结果。本文的可执行示例用本地输出展示了这条流程,也提供了适用于获准应用的实时API分支。

只有在授权流程确实需要住宅网络出口时,才加入Socks5.IO,并在实际客户端中检查路由。真正有价值的交付物是可比较、可解释的报价记录,而不是一份无法证明价格含义的大CSV。

常见问题

仅仅能看到公开页面,不代表自动化采集已经获准。eBay用户协议要求自动访问前取得事先明确许可,API还有独立条件。适用法律、采集字段和使用目的也会影响判断。应选择获得批准的路径,遵守使用范围,排除买家个人信息。商业研究应获取适当的专业意见,不能把教程当作普遍授权。

最新文章

全球代理 IP 网络示意

立即接入全球代理 IP 网络,让每一次连接更快更稳

开始免费试用