チュートリアル

eBayスクレイピングをPythonで行う方法:API、CSV出力とプロキシ設定

eBayの商品データをPythonで取得する手順を解説。Browse APIの認証、ページング、重複排除、CSV出力を実装し、許可済みHTMLの解析と必要な場合のSOCKS5プロキシ設定も確認します。

Gideon ReedGideon Reed約21分で読める

eBayの商品データを調べるなら、まず利用が認められたデータソースを選びます。取得後は商品価格だけでなく、コンディション、バリエーション、送料、配送先、取得時刻を残してください。比較条件がそろわない出品は、安値として集計せず確認対象に分けます。

本記事では、認可されたBrowse APIを使うPythonプログラムを中心に、認証、ページング、重複排除、CSV出力まで扱います。許可を得て保存したHTMLの解析と、必要な場合のSOCKS5プロキシの出口確認も別の手順として説明します。

最初に試すこと: 以下の完全なプログラムを保存し、まず --self-test、次に --demo を実行します。デモはローカルのAPI形式テストデータを使い、CSVと実行ログを作ります。承認済みの本番アプリがある場合だけ --live に切り替えます。

execution-results

1.スクレイピングの前にデータソースを選ぶ

eBayの公開ページを閲覧できることと、自動取得を許可されていることは別です。 eBayのUser Agreementは、自動アクセスに事前の明示的な許可を求めています。APIには別の利用条件があります。プロキシの契約も取得許可の代わりにはなりません。

データソース 利用できる内容 導入時の確認点
利用承認を得たBrowse API 現在の出品を構造化データとして検索し、対応する詳細項目を取得 アプリの権限、OAuth、割り当て上限、レスポンス形式
許可を得て保存したHTML 保存時点のページに実際にある項目を解析 セレクターの保守、取得元と取得時刻の保存
管理されたデータサービス 契約範囲内の項目と更新頻度 出所、利用範囲、検証コスト、納品条件
プロキシ接続 許可された処理のネットワーク経路 接続、出口地域、セッションの確認。データソースではない

価格調査にはどのeBayデータソースを使うべきですか?

必要な項目と配送条件を取得できるなら、承認済みの構造化データソースを使います。Browse APIの検索リファレンスには q、limit、offset と商品概要の項目が示されています。1ページの上限は200件、1つの結果セットの上限は10,000件です。以下のプログラムは検索結果を無制限に追わず、最大3ページに制限します。

調べたい項目 検索結果の概要でできること 詳細APIなどが必要な場面
タイトル、商品ID、表示価格 返された項目を保持 必要なときだけ追加情報を取得
コンディション、出品者識別情報 取得できた値と欠損を記録 承認済みの方法で詳細を確認
選択されたバリエーション 商品・バリエーションの識別子を保持 概要だけで全バリエーションの取得完了とは判断しない
送料・配送条件 配送先を指定し、不明な条件は要確認にする 対象出品と配送先の適用条件を確認
落札・販売価格や売上 出品価格や入札額から推測しない 用途に合う別の承認済みデータが必要

2.Python環境とeBayアプリを準備する

本番APIを使うには開発者資格情報とBuy APIの本番利用資格が必要です。 Sandboxで使えることは本番環境の利用許可を意味しません。Buy APIの本番利用要件を確認し、OAuthのclient credentials手順でアプリトークンを取得します。

Windows PowerShellの場合:

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

Python Launcherがない場合は、意図したPython 3を python --version で確認したうえで、最初のコマンドを python -m venv .venv に替えます。以後は仮想環境のPythonを明示して実行します。

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やログにトークンと秘密鍵は書きません。認証用のHTTPSセッションは直接接続し、任意のプロキシは調査用セッションだけに設定します。

3.リクエストからCSV出力までの4つの処理

リクエスト条件と取得時刻を残し、金額の妥当性を確認してからCSVに書きます。 ここでは要点を示し、次節に実行可能な全コードを載せます。

リクエスト

本番モードでは検索語、件数、オフセットに加え、マーケットプレイスと配送先のヘッダーを指定します。

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 がない場合、商品が空の場合、エラーが出た場合、設定したページ数に達した場合に止まります。次のオフセットは自分で計算し、レスポンスにあるURLを無条件にたどりません。検索ページの結果はトランザクションとして固定されないため、重複排除だけで全件取得を証明することはできません。

4.Browse APIからCSVまでの完全なPythonコード

デモはスクリプト内のローカルJSON形式データを使います。 本番モードだけがアプリトークンを取得し、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.ローカルテストと出力結果を確認する

まずネットワーク不要の自動検査とデモを実行します。 プロキシの環境変数を削除したうえで実行してください。

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

macOS・Linuxでは unset EBAY_PROXY_URL を使い、Pythonのパスを .venv/bin/python に替えます。自動検査は正規化8項目、ページングと出所の確認8項目です。アカウント、ネットワーク、追加のテストファイルは不要です。

保存された実行結果:

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ヘッダーと出力行

次は完全なヘッダーとローカルデータの最初の2行です。時刻は実行記録から取り、実行開始時刻を一括で埋めていません。

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

1行目の商品価格はUSD120.00、送料はUSD8.00で、税金などを除く小計はUSD128.00です。 numeric_ready=True は定義した数値と必須項目の検査を通ったことだけを示します。別の出品と商品が同等であることや、最終決済額を保証するものではありません。

2行目は送料が不明なオークションです。3行目は商品価格がEUR、送料がUSDで、想定通貨USDと一致しません。いずれも理由を添えてCSVに残し、誤って「最安の配送込み価格」として扱わないようにします。

quality-results

重複と時刻はどう扱いますか?

2ページ目には1ページ目の商品が別の価格で再登場します。プログラムは最初の正常な観測を採用し、最初の価格と時刻を保ちます。後の観測を採用する設計に変えるなら、価格だけでなく時刻と出典も含めて行全体を置き換える必要があります。

各ページには observed_utc、取得元URL、検索語、ページ番号、オフセットを記録します。処理が非常に速い場合、複数ページの時計値が同じになることもあります。重要なのはページごとに取得後の時刻を記録することで、人為的に異なる時刻を作ることではありません。

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

このコマンドは米国マーケットプレイスの出品を、米国内の配送先を明示して検索します。Browse APIの配送先設定の説明に、エンコードされた contextualLocation ヘッダーの記載があります。マーケットプレイス、商品の所在地、配送先、プロキシの出口は別々の条件です。一方から他方を推測しないでください。

.run.json にはページ数、重複数、数値比較に使える行数、サンプル種別、実行した経路確認が記録されます。0行なら EMPTY エラーで停止します。後のページで失敗した場合もCSV出力前に止まり、不完全なデータを完全な結果として保存しません。

6.許可を得て保存したHTMLを解析する

HTMLを使う場合は、取得自体が許可されたファイルに限ります。 元の取得時刻とURLを残してください。 parsed_utc はファイルを解析した時刻であり、出品を観測した時刻ではありません。

実際の保存ページを見てセレクターを確認します。次の .s-item と .s-card は互換性を考慮した例で、eBayの恒久的なHTML仕様ではありません。このプログラムはコンディション、通貨、配送情報を補完したふりをせず、すべての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()

許可されたファイルの実際の取得時刻と出典URLを指定します。

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

ローカルの3カードのテストデータは3行を生成しました。バリエーション7を含む固定価格らしいカード、送料がないカード、USD90~100の価格帯を示すカードです。価格帯は両端を文字列として保持し、 price_range を付けます。USD90の確定価格には変えません。ローカル実行時の取得元URLは fixture://html/page/1 です。

ebay-reference

7.必要な場合だけSocks5.IOのプロキシを設定する

承認済みの調査で住宅回線の出口が必要な場合だけ、動的住宅プロキシを検討します。 許可されたAPIに直接接続するだけで目的を達成できることもあります。プロキシは接続経路を提供しますが、アプリの利用資格、欠けた商品項目、自動収集の権利は提供しません。

1.購入した住宅プロキシ製品の「Proxy Setup」を開きます。
2.プロキシのサブアカウント、必要な出口市場、対応プロトコル、セッション方式を選びます。接続先ゲートウェイと実際の出口地域を混同しないでください。
3.生成されたホスト、ポート、プロキシ用ユーザー名、パスワードを控えます。ダッシュボードへのログイン情報とは別です。
4.作業に必要な接続継続時間を選びます。住宅プロキシのセッション設定資料には固定セッションとローテーションの違いがあります。他製品のユーザー名末尾やタイムアウト値を流用せず、現在選択している製品の生成値を使います。

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 はクライアント側で解決します。選んだ製品とクライアントが対応すればHTTP(S)も選択肢です。プロトコルだけでアクセス成功は保証されません。

eBayデータ取得前にSOCKS5の出口地域をどう確認しますか?

Browse APIを呼ぶのと同じRequestsセッションで出口を調べます。 プログラムはIPinfo LiteのAPIで国と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は残しません。2つのセッションでは環境変数からのプロキシ設定の自動継承も無効です。伏せたネットワークが同じでも完全なIPの一致は証明できません。

RoxyBrowserで手動確認する場合も、生成済みのプロトコルと接続項目を使用し、起動したプロファイルの接続は別途確認します。ブラウザーの結果はPythonプロセスの経路を証明しません。

roxy-fields
エラー・症状 確認する順番 判断
407、プロキシ認証エラー 製品の状態→生成ホストとポート→プロキシ資格情報→対応プロトコル 設定を修正してから再確認
DNS・接続エラー ゲートウェイの名前解決→経路→接続先とポート→プロキシ側DNSの対応 失敗箇所を残し、資格情報を含む例外は公開しない
TLSエラー 証明書の信頼と接続先 TLS検証を無効にしない
出口国が違う 同一セッションの検査→選択市場→生成されたユーザー名・セッション設定 地域依存の収集前に停止
APIの401 トークンの設定、期限、スコープ 正しいアプリトークンを取得。無制限の認証再試行はしない
APIの403 アプリの利用資格と許可範囲 出口を切り替えず権限を確認
APIの429 アプリの割り当て上限と実行間隔 停止してサービスの制限に従う
JSON不正、MIME不一致、 itemId 欠損 レスポンス形式とスキーマ 誤解を招くCSVを出力せず停止

8.CSVを比較可能な価格データにする

継続的な価格モニタリングでは、比較対象の条件を先に定義します。 モデルとバリエーション、コンディション、販売方式、通貨、配送先、追加費用を合わせてください。 numeric_ready=True は金額計算と項目の有無を確認した印で、同じ検索語の出品が同等の商品であることは意味しません。

比較項目 扱い
item_id + variation_id 商品・バリエーションの識別と重複排除
コンディション、モデル、バリエーション 同等の商品だけを比較。不明なバリエーションは確認
固定価格とオークション 現在の入札額を固定価格の順位に含めない
商品と送料の通貨 想定通貨と照合し、無断で換算しない
配送先の国と郵便番号 指定した値を保持し、IPから推定しない
商品価格+送料 対応する金額があるときだけ計算。税は小計に含めない
税・決済条件 最終的な配送込み価格と呼ぶ前に適用条件を確認
取得時刻と出典 ページ別の観測と最初に現れた記録を保持

ローカルの3行中、数値比較に進めるのは1行です。残りは送料欠損と通貨不一致で確認が必要です。これは管理したテストデータの品質検査結果であり、eBay全体の欠損率や成功率ではありません。後の検索で見つからなくなった出品を、販売済みと推定してはいけません。

まとめ

eBayスクレイピングの成果は、取得件数よりも比較可能な記録を残せるかで決まります。 承認済みの方法で認証し、ページと配送先の条件を残し、不完全な出品を分けてCSVに出力します。掲載した完全なプログラムはローカルデータで再現できる処理と、承認済みアプリ向けの本番API分岐を備えています。

Socks5.IOを加えるのは、許可された作業に住宅回線の出口が必要な場合だけです。実際にリクエストを送るクライアントで出口を確認してください。大きなCSVより、出典と価格の意味を説明できる出品記録が役立ちます。

よくある質問

公開ページを見られるだけでは自動取得の許可になりません。eBayの契約は自動アクセスに事前の明示的な許可を求め、APIには別の条件があります。法律、収集する項目、利用目的も確認が必要です。承認された方法と範囲を選び、購入者やアカウントの私的情報を除外します。商用調査では個別の法的判断が必要になる場合があります。

最新記事

グローバル プロキシ ネットワークの図

グローバル プロキシ ネットワークに接続 - すべての接続がより速く、より安定します

無料で始める