인프런 커뮤니티 질문&답변
적힌대로 해보고 있는데 크롤링 되다가 멈춥니다.
작성
·
244
1
강의보고 따라하고 있는데
크롤링이 진행되다가 멈추네요
먼저 브랜드 내임만 가져와서 코드가 정상적으로 작동하고 있는지 출력해보았는데 아래와같이 결과가 나오다가 멈추고 정상적으로 작동하면 입력커서가 다시 깜박이어야 하는데 그런것도 없이 멈춰버립니다.
홈플래닛
로지텍
샤오미
홈플래닛
PYHO
샤오미
코시
import requests
from bs4 import BeautifulSoup
main_url = 'https://www.coupang.com/np/search?component=&q=%EB%A7%88%EC%9A%B0%EC%8A%A4&channel=user'
response = requests.get(main_url, headers={'User_Agent' : 'Mozila/5.0'})
html = response.text
soup = BeautifulSoup(html, 'html.parser')
links = soup.select("a.search-product-link")
for link in links:
sub_url = "https://www.coupang.com/" + link.attrs['href']
response = requests.get(sub_url, headers={'User_Agent' : 'Mozila/5.0'})
html = response.text
soup = BeautifulSoup(html, 'html.parser')
brand_name = soup.select_one("a.prod-brand-name").text
print(brand_name)
답변 2
0
스타트코딩
지식공유자
안녕하세요.
for 문을 작성 후에 들여쓰기(Tab)를 해줘야 합니다.
아래 코드를 확인해 보세요 :)
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를 추가하지 않으면 오류가 나요 (멈춰버림)
response = requests.get(main_url, headers={'User-Agent' : 'Mozila/5.0'})
html = response.text
soup = BeautifulSoup(html, 'html.parser')
links = soup.select("a.search-product-link") # select의 결과는 리스트 자료형
for link in links:
sub_url = "https://www.coupang.com/" + link.attrs['href']
response = requests.get(sub_url, headers={'User-Agent' : 'Mozila/5.0'})
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)






지금 확인해 봤는데 오타 다시 한번 확인해 보시겠어요?
언더바(_)가 아니라 대시(-)를 사용해야 합니다.ㅎㅎ
User-Agent