Repository navigation
Expand file tree
/
Copy pathcrawlee-proxy.py
More file actions
58 lines (45 loc) · 1.88 KB
/
Copy pathcrawlee-proxy.py
File metadata and controls
58 lines (45 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python3
"""
Crawlee (Python) HttpCrawler with an HTTP proxy.
Configuration via environment variables:
PROXY_URL - Proxy URL (required), e.g., http://user:pass@proxy:8080
TEST_URL - URL to request (default: https://api.ipify.org?format=json)
Self-hosted ``ProxyConfiguration(proxy_urls=[...])`` with ``HttpCrawler`` (not Apify Proxy).
Documentation: https://crawlee.dev/python/docs/guides/proxy-management
"""
import asyncio
import os
import sys
from crawlee.configuration import Configuration
from crawlee.crawlers import HttpCrawler, HttpCrawlingContext
from crawlee.proxy_configuration import ProxyConfiguration
from crawlee.storage_clients import MemoryStorageClient
proxy_url = os.environ.get('PROXY_URL') or os.environ.get('HTTPS_PROXY')
if not proxy_url:
print('Error: Set PROXY_URL environment variable', file=sys.stderr)
sys.exit(1)
test_url = os.environ.get('TEST_URL', 'https://api.ipify.org?format=json')
async def main() -> None:
proxy_configuration = ProxyConfiguration(proxy_urls=[proxy_url])
crawler = HttpCrawler(
proxy_configuration=proxy_configuration,
max_request_retries=0,
configuration=Configuration(log_level='ERROR'),
storage_client=MemoryStorageClient(),
)
@crawler.router.default_handler
async def handler(context: HttpCrawlingContext) -> None:
body = (await context.http_response.read()).decode('utf-8', errors='replace')
status = context.http_response.status_code
print(f'Status: {status}')
print(f'Body: {body}')
stats = await crawler.run([test_url])
if stats.requests_failed > 0 or stats.requests_finished < 1:
print('Error: request failed', file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
try:
asyncio.run(main())
except Exception as exc:
print(f'Error: {exc}', file=sys.stderr)
sys.exit(1)