Python으로 Amazon 리뷰를 스크랩하는 것은 경쟁사 분석, 리뷰 확인, 시장 조사 등을 수행할 때 유용합니다. 이 문서에서는 Python, BeautifulSoup 및 Requests 라이브러리를 사용하여 Amazon에서 상품 리뷰를 효율적으로 스크랩하는 방법을 보여줍니다.
스크래핑 프로세스를 시작하기 전에 필요한 Python 라이브러리가 설치되어 있는지 확인하세요:
pip install requests
pip install beautifulsoup4
아마존 페이지에서 상품 리뷰를 추출하는 데 중점을 두고 스크래핑 프로세스의 각 단계를 단계별로 살펴보겠습니다.
Amazon 상품 리뷰 페이지의 HTML 구조를 검사하여 스크랩할 요소인 리뷰어 이름, 평점, 댓글을 식별합니다.
제품 제목 및 URL:
총 평점:
검토 섹션:
작성자 이름:
평가:
댓글:
요청 라이브러리를 사용하여 Amazon 상품 리뷰 페이지로 HTTP GET 요청을 전송합니다. 합법적인 브라우저 동작을 모방하고 탐지를 피하도록 헤더를 설정하세요. 프록시와 완전한 요청 헤더는 Amazon에 의해 차단되는 것을 방지하는 데 필수적입니다.
프록시를 사용하면 아마존의 IP 금지 및 속도 제한을 피하기 위해 IP 주소를 순환하는 데 도움이 됩니다. 대규모 스크래핑의 경우 익명성을 유지하고 탐지를 방지하기 위해 프록시를 사용하는 것이 중요합니다. 여기서 프록시 세부 정보는 프록시 서비스에서 제공합니다.
인코딩 허용, 언어 허용, 리퍼러, 연결, 업그레이드-보안 요청과 같은 다양한 헤더를 포함하면 정상적인 브라우저 요청을 모방하여 봇으로 플래그가 지정될 가능성을 줄일 수 있습니다.
import requests
url = "https://www.amazon.com/Portable-Mechanical-Keyboard-MageGee-Backlit/product-reviews/B098LG3N6R/ref=cm_cr_dp_d_show_all_btm?ie=UTF8&reviewerType=all_reviews"
# 프록시 서비스에서 제공하는 프록시 예시
proxy = {
'http': 'http://your_proxy_ip:your_proxy_port',
'https': 'https://your_proxy_ip:your_proxy_port'
}
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 헤더와 프록시를 사용하여 URL로 HTTP GET 요청을 보냅니다.
try:
response = requests.get(url, headers=headers, proxies=proxy, timeout=10)
response.raise_for_status() # Raise an exception for bad response status
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
URL, 제목, 총 평점과 같은 일반적인 제품 세부 정보를 추출하기 위해 BeautifulSoup을 사용하여 응답의 HTML 콘텐츠를 파싱합니다.
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, 'html.parser')
# 공통 제품 세부 정보 추출
product_url = soup.find('a', {'data-hook': 'product-link'}).get('href', '')
product_title = soup.find('a', {'data-hook': 'product-link'}).get_text(strip=True)
total_rating = soup.find('span', {'data-hook': 'rating-out-of-text'}).get_text(strip=True)
식별된 XPath 표현식을 기반으로 HTML 콘텐츠를 계속 구문 분석하여 리뷰어 이름, 평점 및 댓글을 추출합니다.
reviews = []
review_elements = soup.find_all('div', {'data-hook': 'review'})
for review in review_elements:
author_name = review.find('span', class_='a-profile-name').get_text(strip=True)
rating_given = review.find('i', class_='review-rating').get_text(strip=True)
comment = review.find('span', class_='review-text').get_text(strip=True)
reviews.append({
'Product URL': product_url,
'Product Title': product_title,
'Total Rating': total_rating,
'Author': author_name,
'Rating': rating_given,
'Comment': comment,
})
Python에 내장된 CSV 모듈을 사용하여 추출된 데이터를 CSV 파일로 저장하여 추가 분석할 수 있습니다.
import csv
# CSV 파일 경로 정의
csv_file = 'amazon_reviews.csv'
# CSV 필드명 정의
fieldnames = ['Product URL', 'Product Title', 'Total Rating', 'Author', 'Rating', 'Comment']
# CSV 파일에 데이터 쓰기
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for review in reviews:
writer.writerow(review)
print(f"Data saved to {csv_file}")
다음은 Amazon 리뷰 데이터를 스크랩하여 CSV 파일에 저장하는 전체 코드입니다:
import requests
from bs4 import BeautifulSoup
import csv
import urllib3
urllib3.disable_warnings()
# 아마존 상품 리뷰 페이지의 URL
url = "https://www.amazon.com/Portable-Mechanical-Keyboard-MageGee-Backlit/product-reviews/B098LG3N6R/ref=cm_cr_dp_d_show_all_btm?ie=UTF8&reviewerType=all_reviews"
# IP 인증으로 프록시 서비스에서 제공하는 프록시
path_proxy = 'your_proxy_ip:your_proxy_port'
proxy = {
'http': f'http://{path_proxy}',
'https': f'https://{path_proxy}'
}
# HTTP 요청에 대한 헤더
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 헤더와 함께 HTTP GET 요청을 URL로 전송하고 예외를 처리합니다.
try:
response = requests.get(url, headers=headers, timeout=10, proxies=proxy, verify=False)
response.raise_for_status() # Raise an exception for bad response status
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# BeautifulSoup을 사용하여 HTML 콘텐츠 구문 분석하기
soup = BeautifulSoup(response.content, 'html.parser')
# 공통 제품 세부 정보 추출
product_url = soup.find('a', {'data-hook': 'product-link'}).get('href', '') # Extract product URL
product_title = soup.find('a', {'data-hook': 'product-link'}).get_text(strip=True) # Extract product title
total_rating = soup.find('span', {'data-hook': 'rating-out-of-text'}).get_text(strip=True) # Extract total rating
# 개별 리뷰 추출
reviews = []
review_elements = soup.find_all('div', {'data-hook': 'review'})
for review in review_elements:
author_name = review.find('span', class_='a-profile-name').get_text(strip=True) # Extract author name
rating_given = review.find('i', class_='review-rating').get_text(strip=True) # Extract rating given
comment = review.find('span', class_='review-text').get_text(strip=True) # Extract review comment
# 각 리뷰를 사전에 저장
reviews.append({
'Product URL': product_url,
'Product Title': product_title,
'Total Rating': total_rating,
'Author': author_name,
'Rating': rating_given,
'Comment': comment,
})
# CSV 파일 경로 정의
csv_file = 'amazon_reviews.csv'
# CSV 필드명 정의
fieldnames = ['Product URL', 'Product Title', 'Total Rating', 'Author', 'Rating', 'Comment']
# CSV 파일에 데이터 쓰기
with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for review in reviews:
writer.writerow(review)
# 확인 메시지 인쇄
print(f"Data saved to {csv_file}")
결론적으로, 신뢰할 수 있는 프록시 서버를 선택하는 것이 웹 스크래핑을 위한 스크립트 작성의 핵심 단계라는 점을 강조하는 것이 중요합니다. 이를 통해 차단을 효과적으로 우회하고 봇 방지 필터로부터 보호할 수 있습니다. 스크래핑에 가장 적합한 옵션은 높은 신뢰도와 동적 IP 주소를 제공하는 주거용 프록시 서버와 빠른 속도와 운영 안정성을 제공하는 정적 ISP 프록시입니다.
댓글: 0