-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_async_scraping.py
More file actions
83 lines (61 loc) · 1.96 KB
/
02_async_scraping.py
File metadata and controls
83 lines (61 loc) · 1.96 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
#!/usr/bin/env python3
"""Asynchronous scraping examples.
Run: python 02_async_scraping.py
"""
import asyncio
import time
import easyscrape as es
from easyscrape import async_scrape, async_scrape_many, Config
async def single_async():
"""Single async request."""
result = await async_scrape("https://httpbin.org/delay/1")
print(f"Status: {result.status_code}")
async def batch_async():
"""Batch async requests with progress."""
urls = [
f"https://httpbin.org/anything/{i}"
for i in range(10)
]
config = Config(
concurrent_limit=5,
rate_limit=10.0,
)
start = time.time()
count = 0
async for result in async_scrape_many(urls, config=config):
count += 1
print(f" [{count}/{len(urls)}] {result.url} -> {result.status_code}")
elapsed = time.time() - start
print(f"\n Completed {count} requests in {elapsed:.2f}s")
print(f" ({count/elapsed:.1f} requests/second)")
async def compare_sync_vs_async():
"""Compare sync vs async performance."""
urls = [f"https://httpbin.org/delay/0.1" for _ in range(5)]
# Sync (sequential)
start = time.time()
for url in urls:
es.scrape(url)
sync_time = time.time() - start
# Async (concurrent)
start = time.time()
async for _ in async_scrape_many(urls, config=Config(concurrent_limit=5)):
pass
async_time = time.time() - start
print(f" Sync (sequential): {sync_time:.2f}s")
print(f" Async (concurrent): {async_time:.2f}s")
print(f" Speedup: {sync_time/async_time:.1f}x")
def main():
print("=" * 60)
print(" Async Scraping Examples")
print("=" * 60)
print("\n1. Single Async Request")
print("-" * 40)
asyncio.run(single_async())
print("\n2. Batch Async Requests")
print("-" * 40)
asyncio.run(batch_async())
print("\n3. Sync vs Async Comparison")
print("-" * 40)
asyncio.run(compare_sync_vs_async())
if __name__ == "__main__":
main()