-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.py
More file actions
56 lines (41 loc) · 2 KB
/
Copy pathmain2.py
File metadata and controls
56 lines (41 loc) · 2 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
import requests
from bs4 import BeautifulSoup
import csv
# Function to scrape additional information from a product URL
def scrape_product_details(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# Extract additional information
asin_element = soup.find('th', string='ASIN')
asin = asin_element.find_next_sibling(
'td').text.strip() if asin_element else 'N/A'
product_description_element = soup.find(
'div', {'id': 'productDescription'})
product_description = product_description_element.text.strip(
) if product_description_element else 'N/A'
manufacturer_element = soup.find('a', {'id': 'bylineInfo'})
manufacturer = manufacturer_element.text.strip() if manufacturer_element else 'N/A'
return asin, product_description, manufacturer
# Read the CSV file containing the product listings
filename = 'product_listings.csv'
product_listings = []
with open(filename, 'r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
next(reader) # Skip header row
product_listings = list(reader)
# Scrape additional information for each product URL
all_products_details = []
for product in product_listings:
url = product[0]
details = scrape_product_details(url)
all_products_details.append(product + list(details))
# Export the updated data to a new CSV file
updated_filename = 'product_details.csv'
with open(updated_filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Product URL', 'Product Name', 'Product Price', 'Rating',
'Number of Reviews', 'ASIN', 'Product Description', 'Manufacturer'])
writer.writerows(all_products_details)
print('Product details scraped and saved to', updated_filename)