-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamazon_scraper.py
293 lines (249 loc) · 11.1 KB
/
amazon_scraper.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import json
import os
from bs4 import BeautifulSoup
import asyncio
from typing import Optional, Dict, List
import pandas as pd
from helpers import (
AmazonFilterFormatType,
AmazonFilterMediaType,
AmazonFilterSortBy,
AmazonFilterStarRating,
extract_float_from_phrase,
extract_integer,
parse_review_date_and_country,
parse_reviews_count,
)
from amazon_product import AmazonProduct
from amazon_review import AmazonReview
from scraping_config import ScrapingConfig
from http_methods import HttpMethods
from tqdm import tqdm
class AmazonScraper:
def __init__(self, config: Optional[ScrapingConfig] = None):
self.config = config or ScrapingConfig()
self.http_methods = HttpMethods(config=self.config)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.http_methods:
await self.http_methods.session.close()
def __parse_review(self, review_element: BeautifulSoup) -> Optional[AmazonReview]:
"""Parse a single review"""
try:
review = AmazonReview()
# Get review ID
review.id = review_element.get("id")
if not review.id:
return None
# Get review title and rating
rating_element = review_element.find(
"i", {"data-hook": "review-star-rating"}
)
if not rating_element:
rating_element = review_element.find(
"i", {"data-hook": "cmps-review-star-rating"}
)
if rating_element:
review.rating = extract_float_from_phrase(rating_element.get_text())
# Get title
title_element = review_element.find("a", {"data-hook": "review-title"})
if not title_element:
title_element = review_element.find(
"span", {"data-hook": "review-title"}
)
if title_element:
review.href = title_element.get("href")
if review.href:
spans = title_element.find_all("span")
if spans and len(spans) >= 3:
review.title = spans[2].get_text().strip()
else:
review.title = title_element.get_text().strip()
# Get review date and country
date_element = review_element.find("span", {"data-hook": "review-date"})
if date_element:
date_info = parse_review_date_and_country(date_element.get_text())
if date_info:
review.country = date_info["country"]
review.date = date_info["date"]
# Get review body
body_element = review_element.find("span", {"data-hook": "review-body"})
if body_element:
review.body = body_element.get_text().strip()
# Check if verified purchase
verified_element = review_element.find("span", {"data-hook": "avp-badge"})
review.verified_purchase = bool(verified_element)
# Get helpful votes
helpful_element = review_element.find(
"span", {"data-hook": "helpful-vote-statement"}
)
if helpful_element:
text = helpful_element.get_text()
if "One" in text:
review.found_helpful = 1
else:
review.found_helpful = (
extract_integer(helpful_element.get_text()) or 0
)
# Get username
username_element = review_element.find("span", {"class": "a-profile-name"})
if username_element:
review.username = username_element.get_text()
username_url = username_element.find_parent("a")
if username_url:
review.username_url = username_url.get("href")
# Get images
image_elements = review_element.find_all(
"img", {"data-hook": "review-image-tile"}
)
if image_elements:
for element in image_elements:
src = element.get("src")
if src:
review.images.append(src)
other_countries_images_elements = review_element.find_all(
"img", {"data-hook": "cmps-review-image-tile"}
)
if other_countries_images_elements:
for element in other_countries_images_elements:
src = element.get("src")
if src:
review.images.append(src)
# Get videos
if body_element:
video_elements = body_element.find_all(
"div", {"data-review-id": review.id}
)
if video_elements:
for element in video_elements:
src = element.get("data-video-url")
if src:
review.videos.append(src)
return review
except Exception as e:
print(f"Error parsing review: {e}")
return None
async def __process_page(
self, url: str, asin: str, semaphore: asyncio.Semaphore
) -> tuple[str, Optional[str]]:
"""Process a single page with semaphore control"""
async with semaphore:
content = await self.http_methods.get_and_download_url(url)
return url, content
async def __scrape_product_reviews(
self,
asin: str,
semaphore: asyncio.Semaphore,
target_df: pd.DataFrame,
progress_bar: Optional[tqdm] = None,
) -> AmazonProduct:
tasks = []
# Generate all URLs first
for sort_by in AmazonFilterSortBy:
for star_rating in AmazonFilterStarRating:
for format_type in AmazonFilterFormatType:
for media_type in AmazonFilterMediaType:
for page_number in range(1, self.config.max_pages + 1):
url = f"https://www.amazon.com/product-reviews/{asin}?sortBy={sort_by.value}&pageNumber={page_number}&filterByStar={star_rating.value}&formatType={format_type.value}&mediaType={media_type.value}"
tasks.append(self.__process_page(url, asin, semaphore))
# Process all pages concurrently
results = await asyncio.gather(*tasks)
product = AmazonProduct(asin=asin)
# Process results
for url, page_content in results:
if progress_bar:
progress_bar.update(1)
if not page_content:
product.failed_urls.append(url)
continue
soup = BeautifulSoup(page_content, "html.parser")
# Update product info if not already set
if product.name == "":
product_element = soup.find("a", {"data-hook": "product-link"})
if product_element:
product.name = product_element.get_text().strip()
if product.overall_rating == 0:
rating_element = soup.find("span", {"data-hook": "rating-out-of-text"})
if rating_element:
product.overall_rating = extract_float_from_phrase(
rating_element.get_text()
)
rating_count_element = soup.find("div", {"data-hook": "total-review-count"})
if rating_count_element:
count = extract_integer(rating_count_element.get_text())
if count > product.total_rating_count:
product.total_rating_count = count
total_reviews_count_element = soup.find(
"div", {"data-hook": "cr-filter-info-review-rating-count"}
)
if total_reviews_count_element:
count = parse_reviews_count(total_reviews_count_element.get_text())
if count > product.total_reviews_count:
product.total_reviews_count = count
# Parse reviews
review_elements = soup.find_all("div", {"data-hook": "review"})
for review_element in review_elements:
review = self.__parse_review(review_element)
if review:
review.found_under.append(url)
existing_review = next(
(r for r in product.review_list if r.id == review.id), None
)
if existing_review:
if url not in existing_review.found_under:
existing_review.found_under.append(url)
else:
product.review_list.append(review)
self.__mark_complete(df=target_df, product=product)
return product
def __mark_complete(self, df: pd.DataFrame, product: AmazonProduct):
print(
f"Found {len(product.review_list)} unique reviews for ASIN {product.asin}"
)
# Ensure the directory exists
output_dir = "./data/pfw/results/"
os.makedirs(output_dir, exist_ok=True)
# Write product data to a JSON file
file_path = os.path.join(output_dir, f"{product['asin']}.json")
with open(file_path, "w") as json_file:
json.dump(product.to_dict(), json_file, indent=4)
print(f"File successfully created: {file_path}")
if len(product.review_list) == 0:
print(f"no reviews found for: {product.asin}")
return
# Update the `review_complete` column for the current chunk
asin_index = df.index[df["asin"] == product.asin]
df.loc[asin_index, "review_complete"] = 1
# Save updated DataFrame to a file (e.g., a checkpoint)
df.to_pickle("./data/pfw/04_extract_reviews.pkl")
df.to_csv("./data/pfw/04_extract_reviews.csv")
print("Marked as complete and saved to disk.")
async def scrape_asins(self, asins: List[str], target_df: pd.DataFrame):
# Calculate total pages across all ASINs
pages_per_asin = (
len(AmazonFilterSortBy)
* len(AmazonFilterStarRating)
* len(AmazonFilterFormatType)
* len(AmazonFilterMediaType)
* self.config.max_pages
)
total_pages = len(asins) * pages_per_asin
# Create progress bar
progress_bar = tqdm(
total=total_pages, desc="Scraping Progress", position=0, leave=True
)
# Create semaphore for controlling concurrent requests
semaphore = asyncio.Semaphore(self.config.max_concurrent_requests)
# Process all ASINs concurrently
tasks = [
self.__scrape_product_reviews(asin, semaphore, target_df, progress_bar)
for asin in asins
]
# products = await asyncio.gather(*tasks)
await asyncio.gather(*tasks)
progress_bar.close()
# return [product.to_dict() for product in products if product]
def scrape_asins_concurrently(self, asins: List[str]) -> List[Dict]:
"""Synchronous wrapper for backwards compatibility"""
return asyncio.run(self.scrape_asins(asins))