Amazon 제품 페이지 URL에서 특정 정보를 추출하는 웹 스크래핑 함수를 만들어 볼 겁니다.
# Function to scrape product data
def scrape_amazon_product(url):
# Open URL
driver.get(url)
time.sleep(3)
# Get ASIN
asin = get_asin_from_url(url)
# Extract Product Title
try:
title = driver.find_element(By.ID, "productTitle").text.strip()
except:
title = "N/A"
# Extract Brand Name
try:
brand = driver.find_element(By.ID, "bylineInfo").text.replace("Visit the ", "").replace(" Store", "")
except:
brand = "N/A"
# Check for Amazon's Choice label
try:
amazon_choice = driver.find_element(By.CLASS_NAME, 'ac-badge-wrapper')
amazon_choice_exists = "Yes" if amazon_choice else "No"
except:
amazon_choice_exists = "No"
# Extract Star Rating
try:
star_rating = driver.find_element(By.CSS_SELECTOR, "#acrPopover span.a-size-base.a-color-base")
star_rating = float(star_rating.text.strip())
except:
star_rating = "N/A"
# Extract Rating Count
try:
rating_count = driver.find_element(By.ID, "acrCustomerReviewText").text.split()[0]
rating_count = int(rating_count.split()[0].replace(',', ''))
except:
rating_count = "N/A"
# Extract the second rufus question
try:
# Find all the question buttons
question_buttons = driver.find_elements(By.CSS_SELECTOR, 'span.a-declarative button.small-widget-pill')
second_rufus_question = question_buttons[1].text if len(question_buttons) > 1 else "N/A"
except:
second_rufus_question = "N/A"
# Extract Coupon Discount
try:
coupon_discount_text = driver.find_element(By.XPATH, "//label[contains(@id, 'couponText')]").text.strip()
# Split the text and check for percentage
# parts = ["Apply", "25%", "off", "coupon"]
parts = coupon_discount_text.split()
if len(parts) > 1 and '%' in parts[1]:
coupon_discount = parts[1]
else:
coupon_discount = "N/A"
except:
coupon_discount = "N/A"
# Scrape Time
scrape_time = time.strftime("%Y-%m-%d %H:%M:%S")
# Returns a list
return [asin, title, brand, amazon_choice_exists, star_rating, rating_count, second_rufus_question, coupon_discount, scrape_time]
url을 입력 받아 제품 정보를 스크래핑 하는 함수입니다. 우선, driver.get(url)을 이용해 해당 페이지를 엽니다.
get_asin_from_url(url) 함수를 이용하여 ASIN 값을 추출합니다. url의 형태는 https://www.amazon.com/dp/B0CCW6WLJ9 로 B0CCW6WLJ9 부분이 ASIN 값입니다.
def get_asin_from_url(url):
if "/dp/" in url:
asin = url.split("/dp/")[1].split("/")[0]
return asin
return "N/A"
우선, URL 안에 "/dp/"라는 문자열이 포함되어 있는지 확인합니다. 아마존의 제품 상세 페이지 URL은 보통 /dp/ASIN_CODE/ 형식을 따르므로, 이 부분을 찾습니다. 그 후, split을 사용하여 /dp/를 기준으로 문자열을 두 부분으로 나누면 ['https://www.amazon.com', 'B0CCW6WLJ9']이 됩니다. 두 번째 부분인 'B0CCW6WLJ9'을 가져옵니다. 그 후에, split("/")을 사용하여 'B0CCW6WLJ9'을 한 번 더 나누면, 결과는 ['B0CCW6WLJ9']가 됩니다. 여기서 첫 번째 요소인 ['B0CCW6WLJ9'][0]를 추출하여 ASIN 코드인 "B0CCW6WLJ9"을 얻을 수 있습니다. 만약 URL이 /dp/를 포함하지 않으면 "N/A"를 반환합니다.
위의 방식으로 ASIN을 추출할 수도 있고, Selenium을 사용하여 동일한 정보를 추출할 수 있습니다.
try:
asin2 = driver.find_element(By.XPATH, "//th[text() = ' ASIN ' ]/following-sibling::td").text
except:
asin2 = "N/A"
XPath는 XML 문서 내의 요소들을 찾거나 선택하기 위한 언어입니다. 주로 HTML과 XML 구조에서 특정 요소를 선택하기 위해 사용됩니다.
/:
- 경로의 루트(root)부터 시작하는 절대 경로를 나타냅니다.
- 예: /html/body/div → HTML 문서의 최상위 <html> 요소에서 시작하여 <body>와 <div> 요소를 차례대로 찾아갑니다.
//:
- 문서 내 어디에서든지 해당 요소를 찾겠다는 의미입니다. 이는 절대 경로가 아니라 상대 경로입니다.
- 예: //div → 페이지 내의 모든 <div> 요소를 찾습니다.
[]:
- 조건을 지정하여 특정 요소를 찾습니다.
- 예: //div[@class='product'] → class 속성이 product인 모든 <div> 요소를 찾습니다.
@:
- 속성(attribute)을 선택할 때 사용합니다.
- 예: //a[@href='example.com'] → href 속성이 example.com인 <a> 요소를 찾습니다.
text():
- 요소 내의 텍스트 콘텐츠를 선택합니다.
- 예: //h1[text()='Hello World'] → 텍스트 내용이 Hello World인 <h1> 요소를 찾습니다.
//th[text()=' ASIN ']은 th 태그 중에서 텍스트가 ' ASIN '인 요소를 찾습니다 //를 사용해 문서 전체에서 th 태그를 찾습니다. [text()=' ASIN ']는 th 태그 안에 정확히 ' ASIN '라는 텍스트를 가진 요소를 찾습니다. /following-sibling::td 부분은 th 태그로부터 "형제"인 td 태그를 찾습니다. /는 바로 다음 형제 요소를 의미합니다. following-sibling::td는 th 태그의 다음 형제 요소 중에서 td 태그를 찾습니다.
다음 포스팅에서 이어집니다.
'Computer Science > Project' 카테고리의 다른 글
파이썬 프로젝트 (아마존 웹사이트 웹 스크래핑) 7 | 엑셀에 데이터 저장하기 (0) | 2025.03.22 |
---|---|
파이썬 프로젝트 (아마존 웹사이트 웹 스크래핑) 6 | Selenium으로 제품 정보 수집하기 (2) (0) | 2025.03.21 |
파이썬 프로젝트 (아마존 웹사이트 웹 스크래핑) 4 | Selenium을 사용하여 아마존 로그인 자동화하기 (0) | 2025.03.19 |
파이썬 프로젝트 (아마존 웹사이트 웹 스크래핑) 3 | 크롬 옵션 설정 (0) | 2025.03.18 |
파이썬 프로젝트 (아마존 웹사이트 웹 스크래핑) 2 | 프로젝트 개요, Selenium (0) | 2025.03.17 |