파이썬으로 전자상거래 웹사이트 스크래핑하는 방법

댓글: 0

경쟁 분석, 가격 모니터링, 시장 조사를 위해서는 이커머스 웹사이트에서 제품 데이터를 스크랩하는 것이 중요합니다. Python을 사용하면 제품 페이지에서 데이터를 효율적으로 스크랩할 수 있습니다. 이 가이드에서는 요청과 lxml의 조합을 사용해 온라인 스토어에서 제품 정보를 스크랩하는 방법을 보여드립니다.

이커머스 스크래핑에는 온라인 스토어에서 이름, 가격, ID와 같은 제품 세부 정보를 추출하는 작업이 포함됩니다. 다양한 라이브러리를 갖춘 Python을 사용하면 이 작업을 효율적이고 간단하게 수행할 수 있습니다. 이 가이드에서는 코스트코 웹사이트에서 제품 정보를 스크랩해 보겠습니다.

제품 데이터 추출을 위한 스크립트 작성

스크래핑 프로세스를 시작하기 전에 필요한 Python 라이브러리가 설치되어 있는지 확인하세요:

pip install requests
pip install lxml

웹사이트의 특정 제품 페이지에서 제품 이름, 제품 기능 및 제품 브랜드를 추출하는 데 중점을 둡니다.

1단계. 웹사이트의 HTML 구조 이해하기

웹사이트에서 데이터를 추출하려면 웹페이지의 구조를 이해해야 합니다. 웹 사이트 페이지를 열고 스크랩하려는 요소(예: 제품 이름, 기능 브랜드 등)를 검사합니다.

2단계. HTTP 요청 보내기

먼저 요청 라이브러리를 사용하여 제품 페이지에 HTTP GET 요청을 보내겠습니다. 또한 실제 브라우저 요청을 모방하도록 요청 헤더를 설정합니다.


import requests

# 스크랩할 제품 URL 목록
urls = [
    "https://www.costco.com/kirkland-signature-men's-sneaker.product.4000216649.html",
    "https://www.costco.com/adidas-ladies'-puremotion-shoe.product.4000177646.html"
]

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을 반복하여 GET 요청을 보냅니다.
for url in urls:
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        html_content = response.text
        # 후속 단계에서 추가 처리가 추가됩니다.
    else:
        print(f"Failed to retrieve {url}. Status code: {response.status_code}")

3단계. XPath 및 lxml을 사용하여 데이터 추출

lxml을 사용하여 구문 분석된 HTML에서 필요한 데이터 포인트를 추출합니다.

from lxml import html

# 스크랩한 데이터를 저장할 목록
scraped_data = []

# 각 URL을 반복하여 GET 요청을 보냅니다.
for url in urls:
    response = requests.get(url)
    if response.status_code == 200:
        html_content = response.content
        # lxml로 HTML 콘텐츠 구문 분석
        tree = html.fromstring(html_content)
        
        # XPath를 사용하여 데이터 추출
        product_name = tree.xpath('//h1[@automation-id="productName"]/text()')[0].strip()
        product_feature = tree.xpath('//ul[@class="pdp-features"]//li//text()')
        product_brand = tree.xpath('//div[@itemprop="brand"]/text()')[0].strip()
        
        # 추출한 데이터를 목록에 추가하기
        scraped_data.append({'Product Name': product_name, 'Product Feature': product_feature, 'Brand': product_brand})
    else:
        print(f"Failed to retrieve {url}. Status code: {response.status_code}")

# 스크랩한 데이터 인쇄
for item in scraped_data:
    print(item)

4단계. 잠재적 문제 해결

웹사이트는 종종 봇 방지 조치를 구현합니다. 프록시를 사용하고 사용자 에이전트를 교체하면 탐지를 피하는 데 도움이 될 수 있습니다.

IP 인증과 함께 프록시 사용:


proxies = {
    'http': 'http://your_proxy_ip:your_proxy_port',
    'https': 'https://your_proxy_ip:your_proxy_port'
}
response = requests.get(url, proxies=proxies)

사용자 에이전트 교체:


import random

user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    # 필요에 따라 사용자 에이전트 추가
]

headers['user-agent'] = random.choice(user_agents)

response = requests.get(url, headers=headers)

5단계. 데이터를 CSV 파일로 저장

마지막으로 추가 분석을 위해 스크랩한 데이터를 CSV 파일에 저장합니다.

import csv

csv_file = 'costco_products.csv'
fieldnames = ['Product Name', 'Product Feature', 'Brand']

# CSV 파일에 데이터 쓰기
try:
    with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        for item in scraped_data:
            writer.writerow(item)
    print(f"Data saved to {csv_file}")
except IOError:
    print(f"Error occurred while writing data to {csv_file}")

코드 완성


import requests
import urllib3
from lxml import html
import csv
import random
import ssl

ssl._create_default_https_context = ssl._create_stdlib_context
urllib3.disable_warnings()

# 스크랩할 제품 URL 목록
urls = [
   "https://www.costco.com/kirkland-signature-men's-sneaker.product.4000216649.html",
   "https://www.costco.com/adidas-ladies'-puremotion-shoe.product.4000177646.html"
]

# 헤더
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',
}

# 로테이션 요청에 대한 사용자 에이전트 목록
user_agents = [
   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
   # 필요에 따라 사용자 에이전트 추가
]


# 로테이션 요청에 대한 프록시 목록
proxies = [
    {'http': 'http://your_proxy_ip:your_proxy_port', 'https': 'https://your_proxy_ip:your_proxy_port'},
    {'http': 'http://your_proxy_ip2:your_proxy_port2', 'https': 'https://your_proxy_ip2:your_proxy_port2'},
    # 필요에 따라 프록시 추가
]

# 스크랩한 데이터를 저장할 목록
scraped_data = []

# 각 URL을 반복하여 GET 요청을 보냅니다.
for url in urls:
   # 요청 헤더에 대해 임의의 사용자 에이전트를 선택합니다.
   headers['user-agent'] = random.choice(user_agents)
   # 요청에 대한 임의의 프록시 선택
   proxy = random.choice(proxies)

   # 헤더와 프록시를 사용하여 URL로 HTTP GET 요청을 보냅니다.
   response = requests.get(url, headers=headers, proxies=proxy, verify=False)
   if response.status_code == 200:
       # 응답의 HTML 콘텐츠 저장
       html_content = response.content
       # lxml로 HTML 콘텐츠 구문 분석
       tree = html.fromstring(html_content)

       # XPath를 사용하여 데이터 추출
       product_name = tree.xpath('//h1[@automation-id="productName"]/text()')[0].strip()
       product_feature = tree.xpath('//ul[@class="pdp-features"]//li//text()')
       product_brand = tree.xpath('//div[@itemprop="brand"]/text()')[0].strip()

       # 추출한 데이터를 목록에 추가하기
       scraped_data.append({'Product Name': product_name, 'Product Feature': product_feature, 'Brand': product_brand})
   else:
       # 요청 실패 시 오류 메시지 인쇄
       print(f"Failed to retrieve {url}. Status code: {response.status_code}")

# CSV 파일 설정
csv_file = 'costco_products.csv'
fieldnames = ['Product Name', 'Product Feature', 'Brand']

# CSV 파일에 데이터 쓰기
try:
   with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
       writer = csv.DictWriter(file, fieldnames=fieldnames)
       writer.writeheader()
       for item in scraped_data:
           writer.writerow(item)
   print(f"Data saved to {csv_file}")
except IOError:
   # 파일 쓰기에 실패하면 오류 메시지 인쇄
   print(f"Error occurred while writing data to {csv_file}")

Python을 사용하여 Costco와 같은 이커머스 사이트에서 스크래핑하는 것은 제품 정보를 수집하여 분석하고 전략적 의사 결정을 내리는 데 효과적인 방법입니다. 요청과 같은 라이브러리와 Lxml을 적절히 활용하면 봇 방지 API를 효과적으로 구현하면서 HTML 콘텐츠를 처리할 수 있는 자동화된 추출 프로세스를 구현할 수 있습니다. 항상 윤리적 스크래핑 프로토콜을 준수해야 한다는 점에 유의해야 합니다.

댓글:

0 댓글