Repository navigation
Expand file tree
/
Copy pathaiohttp_concurrent.py
More file actions
83 lines (66 loc) · 3.12 KB
/
Copy pathaiohttp_concurrent.py
File metadata and controls
83 lines (66 loc) · 3.12 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""aiohttp: fetch several listing pages at once through a proxy.
aiohttp takes the proxy on each request, so every page can use a different
proxy from the source: the residential gateway, or the next datacenter IP.
A semaphore caps how many requests run at the same time. Parsing reuses the
lxml parser from urllib3_lxml.py.
python examples/aiohttp_concurrent.py --pages 5 --concurrency 3
"""
import argparse
import asyncio
import os
import sys
from typing import List
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.dirname(__file__))
import aiohttp
from books_site import START_URL, Book, listing_urls, print_books, write_csv
from proxy_config import ProxySource, describe, load_dotenv_if_present, proxy_source_from_env
from urllib3_lxml import parse
async def fetch(session: aiohttp.ClientSession, url: str, source: ProxySource, attempts: int = 3, backoff: float = 1.0) -> bytes:
"""Fetch one page, moving to the next proxy from the source on failure."""
for attempt in range(1, attempts + 1):
proxy = source.next()
try:
async with session.get(url, proxy=proxy) as response:
response.raise_for_status()
body = await response.read()
except (aiohttp.ClientError, asyncio.TimeoutError):
source.report_failure(proxy)
if attempt == attempts:
raise
await asyncio.sleep(backoff * attempt)
continue
source.report_success(proxy)
return body
raise AssertionError("unreachable")
async def scrape(urls: List[str], source: ProxySource, concurrency: int = 5, timeout: float = 30, backoff: float = 1.0) -> List[Book]:
semaphore = asyncio.Semaphore(concurrency)
async def one(session: aiohttp.ClientSession, url: str) -> List[Book]:
async with semaphore:
html = await fetch(session, url, source, backoff=backoff)
books, _next = parse(html, url)
return books
client_timeout = aiohttp.ClientTimeout(total=timeout)
async with aiohttp.ClientSession(timeout=client_timeout) as session:
pages = await asyncio.gather(*(one(session, url) for url in urls))
return [book for page in pages for book in page]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--pages", type=int, default=5)
parser.add_argument("--concurrency", type=int, default=5)
parser.add_argument("--proxy-type", choices=["residential", "datacenter"])
parser.add_argument("--start-url", default=START_URL)
parser.add_argument("--csv", metavar="PATH")
args = parser.parse_args()
load_dotenv_if_present()
source = proxy_source_from_env(proxy_type=args.proxy_type)
print("Proxy:", describe(source))
urls = listing_urls(args.pages, args.start_url)
books = asyncio.run(scrape(urls, source, args.concurrency))
print(f"Scraped {len(books)} books from {len(urls)} pages, up to {args.concurrency} at a time:")
print_books(books)
if args.csv:
write_csv(books, args.csv)
print("Saved to", args.csv)
if __name__ == "__main__":
main()