MCPcopy Create free account
hub / github.com/apify/crawlee-python / main

Function main

docs/guides/code_examples/http_headers/set_headers.py:8–29  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

6
7
8async def main() -> None:
9 # Set default headers on the client. They are sent on every request.
10 http_client = ImpitHttpClient(headers={'X-Api-Key': 'secret'})
11
12 crawler = HttpCrawler(http_client=http_client, max_requests_per_crawl=10)
13
14 @crawler.router.default_handler
15 async def request_handler(context: HttpCrawlingContext) -> None:
16 # `httpbin.org/headers` echoes the received request headers back.
17 response = (await context.http_response.read()).decode()
18 context.log.info(f'{context.request.unique_key}: {response}')
19
20 # Add a header for this request only. It merges with the client defaults.
21 request = Request.from_url(
22 'https://httpbin.org/headers',
23 headers=HttpHeaders({'Accept': 'application/json'}),
24 # Both requests target the same URL. Without a distinct `unique_key`,
25 # deduplication would drop this one.
26 unique_key='set-headers-example',
27 )
28
29 await crawler.run(['https://httpbin.org/headers', request])
30
31
32if __name__ == '__main__':

Callers 1

set_headers.pyFile · 0.70

Calls 5

ImpitHttpClientClass · 0.90
HttpCrawlerClass · 0.90
HttpHeadersClass · 0.90
from_urlMethod · 0.80
runMethod · 0.45

Tested by

no test coverage detected