-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamazon.py
71 lines (62 loc) · 2.43 KB
/
amazon.py
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
url = "https://www.amazon.com/s?k=iphone"
from crawl4ai import AsyncWebCrawler, CacheMode
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy
from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig
import json
async def extract_amazon_products():
browswer_config = BrowserConfig(
browser_type="chromium",
headless=True
)
crawler_config = CrawlerRunConfig(
extraction_strategy= JsonCssExtractionStrategy(
schema={
"name": "Amazon product search result",
"baseSelector": "[data-component-type='s-search-result']",
"fields": [
{
"name": "title",
"selector":"h2 span",
"type": "text"
},
{
"name": "image",
"selector": ".s-image",
"type": "attribute",
"attribute": "src"
},
{
"name": "rating",
"selector": ".a-icon-star-small .a-icon-alt",
"type": "text"
},
{
"name": "reviews_count",
"selector": "[data-csa-c-func-deps=aui-da-a-popover]",
"type": "text"
},
{
"name": "price",
"selector": ".a-price .a-offscreen",
"type": "text"
}
]
}
)
)
async with AsyncWebCrawler(config=browswer_config) as crawler:
result = await crawler.arun(url=url, config=crawler_config, cache_mode=CacheMode.BYPASS)
if result and result.extracted_content:
products = json.loads(result.extracted_content)
print(len(products))
for product in products:
print("\n Product Details:")
print(f"Title: {product.get('title')}")
print(f"Price: {product.get('price')}")
print(f"Rating: {product.get('rating')}")
print(f"Image: {product.get('image')}")
print(f"Review Count: {product.get('reviews_count')}")
print("-" * 80)
if __name__== "__main__":
import asyncio
asyncio.run(extract_amazon_products())