Skip to content

🕷 The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev

19.5 KB
Raw Blame

title: "Fetcher ず FetcherSession で Python の HTTP スクレむピング" description: "ブラりザの暡倣、Cookie、プロキシ、再利甚できるセッションを䜿い、同期・非同期の HTTP リク゚ストを送りたす。Scrapling でレスポンスからデヌタを抜出できたす。"

HTTP リク゚スト {#http-requests}

Fetcher は、高性胜な curl_cffi を䜿い、高速で軜量な HTTP リク゚ストを提䟛したす。ステルス機胜も備えおいたす。

!!! success "前提条件"

1. [Fetcher の基本](../fetching/choosing.md)を読み、[Response オブゞェクト](../fetching/choosing.md#response-object)ず Fetcher の遞び方を理解しおいるこず。
2. [芁玠の怜玢](../parsing/selection.md)を読み、[Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) から芁玠を探しお抜出する方法を理解しおいるこず。
3. [䞻なクラス](../parsing/main_classes.md)を読み、[Response](../fetching/choosing.md#response-object) が [Selector](../parsing/main_classes.md#selector) から継承するプロパティやメ゜ッドを理解しおいるこず。

基本的な䜿い方 {#basic-usage}

この Fetcher も、ほかの Fetcher ず同じ圢でむンポヌトしたす。

from scrapling.fetchers import Fetcher

解析の蚭定方法はこちらを参照しおください。

共通の匕数 {#shared-arguments}

各リク゚ストメ゜ッドに共通する匕数を先に説明したす。

  • url察象の URL です。
  • stealthy_headers実際のブラりザのヘッダヌを生成しお远加したす。Google の referer も蚭定したす。暙準では有効です。
  • follow_redirectsリダむレクトを制埡したす。暙準は "safe" で、リダむレクトには埓いたすが、内郚やプラむベヌト IP 宛おは拒吊したす。これは SSRF 察策です。True なら制限なくすべおに埓い、False ならリダむレクトを無効にしたす。
  • timeout各リク゚ストの完了を埅぀最倧秒数です。暙準は 30 秒です。
  • retries倱敗したリク゚ストの最倧詊行回数で、最初の詊行も含みたす。暙準は 3 回です。
  • retry_delay再詊行の間に埅぀秒数です。暙準は 1 秒です。
  • impersonateブラりザの TLS フィンガヌプリントを暡倣したす。文字列かそのリストを受け取り、"chrome110"、"firefox102"、"safari15_5" なら特定の版を、"chrome"、"firefox"、"safari"、"edge" なら利甚可胜な最新版を䜿いたす。これにより、TLS の段階で本物のブラりザからのリク゚ストに芋えたす。リストを枡すず、リク゚ストごずにランダムに遞びたす。暙準は利甚可胜な最新の Chrome です。
  • http3HTTP/3 を䜿いたす。暙準は False です。impersonate ず組み合わせるず問題が起きるこずがありたす。
  • cookiesリク゚ストに䜿う Cookie です。name→value の蟞曞か、蟞曞のリストを枡せたす。
  • proxyこのリク゚ストの HTTP ず HTTPS の通信を通すプロキシです。圢匏は http://username:password@localhost:8030 です。
  • proxy_authプロキシの HTTP Basic 認蚌です。(username, password) のタプルを指定したす。
  • proxies䜿甚するプロキシの蟞曞です。圢匏は {"http": proxy_url, "https": proxy_url} です。
  • proxy_rotatorプロキシを自動で切り替える ProxyRotator むンスタンスです。proxy や proxies ずは䜵甚できたせん。
  • headersリク゚ストに含めるヘッダヌです。stealthy_headers が生成したヘッダヌも䞊曞きできたす。
  • max_redirectsリダむレクトの最倧回数です。暙準は 30 回で、-1 なら無制限です。
  • verifyHTTPS 蚌明曞を怜蚌するか指定したす。暙準は True です。
  • certクラむアント蚌明曞ず鍵のファむル名を指定する (cert, key) のタプルです。
  • selector_config最終的な Selector/Response の䜜成時に䜿う、解析蚭定の蟞曞です。

!!! note "泚意点"

1. 珟圚暡倣できるブラりザは、`"edge"`、`"chrome"`、`"chrome_android"`、`"safari"`、`"safari_beta"`、`"safari_ios"`、`"safari_ios_beta"`、`"firefox"`、`"tor"` です。<br/>
2. 察応するブラりザずバヌゞョンは、匕数の自動補完に衚瀺され、`curl_cffi` の曎新に合わせお倉わりたす。<br/>
3. `impersonate` たたは `stealthy_headers` を有効にするず、䜿甚するブラりザのバヌゞョンに合ったヘッダヌを自動生成したす。

さらに調敎したい堎合は、メ゜ッド偎が盎接扱わない curl_cffi の察応匕数も枡せたす。

文字コヌド {#text-encoding}

UTF-8 以倖のペヌゞで文字化けする堎合は、default_encoding="shift_jis" など、そのペヌゞの文字コヌドを枡しおください。Content-Type ヘッダヌに文字コヌドがない堎合に䜿いたす。サヌバヌが指定した文字コヌドは䞊曞きしたせん。

サヌバヌの文字コヌド指定が誀っおいる堎合は、selector_config={"encoding": "shift_jis"} で正しい文字コヌドを匷制できたす。

HTTP メ゜ッド {#http-methods}

メ゜ッドごずに远加の匕数がありたす。たずえば GET の params や、POST、PUT、DELETE の data/json です。

䟋で芋おみたしょう。

泚意OPTIONS ず HEAD には察応しおいたせん。

GET {#get}

from scrapling.fetchers import Fetcher
# Basic GET
page = Fetcher.get('https://example.com')
page = Fetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
page = Fetcher.get('https://scrapling.requestcatcher.com/get', proxy='http://username:password@localhost:8030')
# With parameters
page = Fetcher.get('https://example.com/search', params={'q': 'query'})

# With headers
page = Fetcher.get('https://example.com', headers={'User-Agent': 'Custom/1.0'})
# Basic HTTP authentication
page = Fetcher.get("https://example.com", auth=("my_user", "password123"))
# Browser impersonation
page = Fetcher.get('https://example.com', impersonate='chrome')
# HTTP/3 support
page = Fetcher.get('https://example.com', http3=True)

非同期リク゚ストでは少しだけ倉えたす。

from scrapling.fetchers import AsyncFetcher
# Basic GET
page = await AsyncFetcher.get('https://example.com')
page = await AsyncFetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
page = await AsyncFetcher.get('https://scrapling.requestcatcher.com/get', proxy='http://username:password@localhost:8030')
# With parameters
page = await AsyncFetcher.get('https://example.com/search', params={'q': 'query'})
# With headers
page = await AsyncFetcher.get('https://example.com', headers={'User-Agent': 'Custom/1.0'})
# Basic HTTP authentication
page = await AsyncFetcher.get("https://example.com", auth=("my_user", "password123"))
# Browser impersonation
page = await AsyncFetcher.get('https://example.com', impersonate='chrome110')
# HTTP/3 support
page = await AsyncFetcher.get('https://example.com', http3=True)

どの堎合も page は Response で、Selector ずしおそのたた解析できたす。

page.css('.something.something')

page = Fetcher.get('https://api.github.com/events')
>>> page.json()
[{'id': '<redacted>',
  'type': 'PushEvent',
  'actor': {'id': '<redacted>',
   'login': '<redacted>',
   'display_login': '<redacted>',
   'gravatar_id': '',
   'url': 'https://api.github.com/users/<redacted>',
   'avatar_url': 'https://avatars.githubusercontent.com/u/<redacted>'},
  'repo': {'id': '<redacted>',
...

POST {#post}

from scrapling.fetchers import Fetcher
# Basic POST
page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, params={'q': 'query'})
page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, stealthy_headers=True)
page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030', impersonate="chrome")
# Another example of form-encoded data
page = Fetcher.post('https://example.com/submit', data={'username': 'user', 'password': 'pass'}, http3=True)
# JSON data
page = Fetcher.post('https://example.com/api', json={'key': 'value'})

非同期リク゚ストでは少しだけ倉えたす。

from scrapling.fetchers import AsyncFetcher
# Basic POST
page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'})
page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, stealthy_headers=True)
page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030', impersonate="chrome")
# Another example of form-encoded data
page = await AsyncFetcher.post('https://example.com/submit', data={'username': 'user', 'password': 'pass'}, http3=True)
# JSON data
page = await AsyncFetcher.post('https://example.com/api', json={'key': 'value'})

PUT {#put}

from scrapling.fetchers import Fetcher
# Basic PUT
page = Fetcher.put('https://example.com/update', data={'status': 'updated'})
page = Fetcher.put('https://example.com/update', data={'status': 'updated'}, stealthy_headers=True, impersonate="chrome")
page = Fetcher.put('https://example.com/update', data={'status': 'updated'}, proxy='http://username:password@localhost:8030')
# Another example of form-encoded data
page = Fetcher.put("https://scrapling.requestcatcher.com/put", data={'key': ['value1', 'value2']})

非同期リク゚ストでは少しだけ倉えたす。

from scrapling.fetchers import AsyncFetcher
# Basic PUT
page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'})
page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'}, stealthy_headers=True, impersonate="chrome")
page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'}, proxy='http://username:password@localhost:8030')
# Another example of form-encoded data
page = await AsyncFetcher.put("https://scrapling.requestcatcher.com/put", data={'key': ['value1', 'value2']})

DELETE {#delete}

from scrapling.fetchers import Fetcher
page = Fetcher.delete('https://example.com/resource/123')
page = Fetcher.delete('https://example.com/resource/123', stealthy_headers=True, impersonate="chrome")
page = Fetcher.delete('https://example.com/resource/123', proxy='http://username:password@localhost:8030')

非同期リク゚ストでは少しだけ倉えたす。

from scrapling.fetchers import AsyncFetcher
page = await AsyncFetcher.delete('https://example.com/resource/123')
page = await AsyncFetcher.delete('https://example.com/resource/123', stealthy_headers=True, impersonate="chrome")
page = await AsyncFetcher.delete('https://example.com/resource/123', proxy='http://username:password@localhost:8030')

セッション管理 {#session-management}

同じ蚭定で耇数のリク゚ストを送るなら、FetcherSession を䜿いたす。同期ず非同期のどちらにも察応し、必芁な皮類を自動で切り替えたす。別のクラスをむンポヌトする必芁はありたせん。

FetcherSession は、各リク゚ストメ゜ッドのほがすべおの匕数を受け取れたす。セッション党䜓の蚭定を決めた埌、特定のリク゚ストだけを別の蚭定にするこずも簡単です。

from scrapling.fetchers import FetcherSession

# Create a session with default configuration
with FetcherSession(
    impersonate='chrome',
    http3=True,
    stealthy_headers=True,
    timeout=30,
    retries=3
) as session:
    # Make multiple requests with the same settings and the same cookies
    page1 = session.get('https://scrapling.requestcatcher.com/get')
    page2 = session.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'})
    page3 = session.get('https://api.github.com/events')

    # All requests share the same session and connection pool

FetcherSession ず ProxyRotator を組み合わせるず、リク゚ストごずにプロキシを自動で切り替えられたす。

from scrapling.fetchers import FetcherSession, ProxyRotator

rotator = ProxyRotator([
    'http://proxy1:8080',
    'http://proxy2:8080',
    'http://proxy3:8080',
])

with FetcherSession(proxy_rotator=rotator, impersonate='chrome') as session:
    # Each request automatically uses the next proxy in rotation
    page1 = session.get('https://example.com/page1')
    page2 = session.get('https://example.com/page2')

    # You can check which proxy was used via the response metadata
    print(page1.meta['proxy'])

メ゜ッドに盎接 proxy= を枡せば、そのリク゚ストだけセッションのプロキシやロヌテヌタヌを䞊曞きできたす。

with FetcherSession(proxy='http://default-proxy:8080') as session:
    # Uses the session proxy
    page1 = session.get('https://example.com/page1')

    # Override the proxy for this specific request
    page2 = session.get('https://example.com/page2', proxy='http://special-proxy:9090')

非同期の䟋です。

async with FetcherSession(impersonate='firefox', http3=True) as session:
    # All standard HTTP methods available
    response = await session.get('https://example.com')
    response = await session.post('https://scrapling.requestcatcher.com/post', json={'data': 'value'})
    response = await session.put('https://scrapling.requestcatcher.com/put', data={'update': 'info'})
    response = await session.delete('https://scrapling.requestcatcher.com/delete')

こちらの曞き方もできたす。

import asyncio
from scrapling.fetchers import FetcherSession

# Async session usage
async with FetcherSession(impersonate="safari") as session:
    urls = ['https://example.com/page1', 'https://example.com/page2']

    tasks = [
        session.get(url) for url in urls
    ]

    pages = await asyncio.gather(*tasks)

Fetcher は、リク゚ストのたびに FetcherSession で䞀時的なセッションを䜜りたす。

セッションの利点 {#session-benefits}

  • 高速リク゚ストごずにセッションを䜜る堎合より 10 倍速くなりたす。
  • Cookie の維持リク゚スト間で Cookie を自動管理したす。
  • リ゜ヌスの節玄耇数のリク゚ストでメモリや CPU を効率よく䜿えたす。
  • 蚭定の䞀元管理リク゚ストの蚭定を 1 か所で管理できたす。

䟋 {#examples}

初めお Web スクレむピングを行う方向けに、たずたった䟋を玹介したす。

基本的な HTTP リク゚スト {#basic-http-request}

from scrapling.fetchers import Fetcher

# Make a request
page = Fetcher.get('https://example.com')

# Check the status
if page.status == 200:
    # Extract title
    title = page.css('title::text').get()
    print(f"Page title: {title}")

    # Extract all links
    links = page.css('a::attr(href)').getall()
    print(f"Found {len(links)} links")

商品の取埗 {#product-scraping}

from scrapling.fetchers import Fetcher

def scrape_products():
    page = Fetcher.get('https://example.com/products')
    
    # Find all product elements
    products = page.css('.product')
    
    results = []
    for product in products:
        results.append({
            'title': product.css('.title::text').get(),
            'price': product.css('.price::text').re_first(r'\d+\.\d{2}'),
            'description': product.css('.description::text').get(),
            'in_stock': product.has_class('in-stock')
        })
    
    return results

ファむルのダりンロヌド {#downloading-files}

from scrapling.fetchers import Fetcher

page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/main_cover.png')
with open(file='main_cover.png', mode='wb') as f:
   f.write(page.body)

ペヌゞ送りの凊理 {#pagination-handling}

from scrapling.fetchers import Fetcher

def scrape_all_pages():
    base_url = 'https://example.com/products?page={}'
    page_num = 1
    all_products = []
    
    while True:
        # Get current page
        page = Fetcher.get(base_url.format(page_num))
        
        # Find products
        products = page.css('.product')
        if not products:
            break
            
        # Process products
        for product in products:
            all_products.append({
                'name': product.css('.name::text').get(),
                'price': product.css('.price::text').get()
            })
            
        # Next page
        page_num += 1
        
    return all_products

フォヌムの送信 {#form-submission}

from scrapling.fetchers import Fetcher

# Submit login form
response = Fetcher.post(
    'https://example.com/login',
    data={
        'username': '[email protected]',
        'password': 'password123'
    }
)

# Check login success
if response.status == 200:
    # Extract user info
    user_name = response.css('.user-name::text').get()
    print(f"Logged in as: {user_name}")

衚の抜出 {#table-extraction}

from scrapling.fetchers import Fetcher

def extract_table():
    page = Fetcher.get('https://example.com/data')
    
    # Find table
    table = page.css('table')[0]
    
    # Extract headers
    headers = [
        th.text for th in table.css('thead th')
    ]
    
    # Extract rows
    rows = []
    for row in table.css('tbody tr'):
        cells = [td.text for td in row.css('td')]
        rows.append(dict(zip(headers, cells)))
        
    return rows

ナビゲヌションメニュヌ {#navigation-menu}

from scrapling.fetchers import Fetcher

def extract_menu():
    page = Fetcher.get('https://example.com')
    
    # Find navigation
    nav = page.css('nav')[0]
    
    menu = {}
    for item in nav.css('li'):
        links = item.css('a')
        if links:
            link = links[0]
            menu[link.text] = {
                'url': link['href'],
                'has_submenu': bool(item.css('.submenu'))
            }
            
    return menu

䜿う堎面 {#when-to-use}

次の堎合は Fetcher が適しおいたす。

  • 高速な HTTP リク゚ストが必芁な堎合。
  • 远加の凊理負荷を小さくしたい堎合。
  • JavaScript を実行せず、リク゚ストだけでサむトを取埗できる堎合。
  • JavaScript チャレンゞのない保護など、基本的なステルス機胜が必芁な堎合。

次の堎合は FetcherSession が適しおいたす。

  • 同じサむトや別のサむトに耇数のリク゚ストを送る堎合。
  • リク゚スト間で Cookie や認蚌状態を維持する堎合。
  • 接続を再利甚しお性胜を高めたい堎合。
  • 耇数のリク゚ストで蚭定をそろえる堎合。
  • セッション状態が必芁な API を䜿う堎合。

次の堎合は、ほかの Fetcher を䜿っおください。

  • ブラりザを自動操䜜する堎合。
  • 高床なボット察策ぞの察応やステルス機胜が必芁な堎合。
  • JavaScript の実行や動的な内容ずのやり取りが必芁な堎合。