• 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    해결됨

쿠팡 첫페이지 관련 href 오류가 뜹니다.

23.12.04 16:50 작성 23.12.04 17:07 수정 조회수 330

1

강의노트에 올려주신 코드를 그대로 복붙해서 실행시켰는데,

C:\CRAWLLING> cmd /C "C:\Users\libra_erv8ij1\AppData\Local\Programs\Python\Python312\python.exe c:\Users\libra_erv8ij1\.vscode\extensions\ms-python.python-2023.20.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher 1693 -- "c:\CRAWLLING\CRAWLING 심화\ch3. 쿠팡크롤링\01.첫번째페이지크롤링.py" "

Traceback (most recent call last):

File "c:\CRAWLLING\CRAWLING 심화\ch3. 쿠팡크롤링\01.첫번째페이지크롤링.py", line 20, in <module>

sub_url = "https://www.coupang.com" + link.attrs['href']

~~~~~~~~~~^^^^^^^^

KeyError: 'href'

href 관련 오류가 나옵니다. 왜그러는걸까요?

 

답변 1

답변을 작성해보세요.

2

사이트가 업데이트 되었습니다.

상세페이지 링크 값이 href에 들어 있지 않고, data-product-link에 있네요.

그리고 베스트 셀러 상품들이 추가 되었는데 얘들은 data-link라는 속성안에 있습니다.

아래 처럼 코드를 수정해 주면 정상적으로 작동 됩니다.

 

import requests
from bs4 import BeautifulSoup

main_url = "https://www.coupang.com/np/search?component=&q=usb%ED%97%88%EB%B8%8C&channel=user"

# 헤더에 User-Agent, Accept-Language 를 추가하지 않으면 멈춥니다
header = {
    'Host': 'www.coupang.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3',
}

response = requests.get(main_url, headers=header)
html = response.text
soup = BeautifulSoup(html, 'html.parser')

links = soup.select("a.search-product-link") # select의 결과는 리스트 자료형
for link in links:
    
    if link.attrs.get('data-product-link'):
        # 일반 상품 링크
        sub_url = "https://www.coupang.com/" + link.attrs['data-product-link']
    else:
        # 베스트셀러 상품 링크
        sub_url = "https://www.coupang.com/" + link.attrs['data-link']

    response = requests.get(sub_url, headers=header)
    html = response.text

    soup = BeautifulSoup(html, 'html.parser')

    # 브랜드명은 있을 수도 있고, 없을 수도 있어요
    # - 중고상품일 때는 태그가 달라져요
    # try - except로 예외처리를 해줍니다
    try:
        brand_name = soup.select_one("a.prod-brand-name").text
    except:
        brand_name = ""
    
    # 상품명
    product_name = soup.select_one("h2.prod-buy-header__title").text

    # 가격
    product_price = soup.select_one("span.total-price > strong").text

    print(brand_name, product_name, product_price)