web_crolling

쩡쓰·2022년 5월 23일
0

데이터분석

목록 보기
1/6

데이터분석에 필요한 데이터 만들기

데이터분석을 하려면 다양한 데이터들이 필요로 하는데 필요한 데이터셋을 직접 만드는 경우가 많이 있다.
그 중에서도 가장 기본적인 방법중 하나가 웹크롤링이다.

웹크롤링

사용언어: python

크롤링대상페이지: www.auction.co.kr


# from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
# BeautifulSoup : 웹페이지의 정보르 쉽게 스크랩할 수 있도록 기능을 제공하는 라이브러리
# 키워드 input
serarch_keyword = "감자칩"
# 크롤링 도구
driver = webdriver.Chrome("./chromedriver")
driver.implicitly_wait(3)
time.sleep(5)

# 오픈마켓 접속
driver.get("http://www.auction.co.kr")
time.sleep(5)

# 상품 검색 키워드
# //*[@id="txtKeyword"]
driver.find_element_by_xpath("//*[@id='txtKeyword']").send_keys(serarch_keyword)
time.sleep(2)
# //*[@id="core_header"]/div/div[1]/form/div[1]/input[2]
# 상품 키워드 검색 버튼 클릭
driver.find_element_by_xpath(
    "//*[@id='core_header']/div/div[1]/form/div[1]/input[2]").click()

# 상품 리스트 정보 가져오기
html = driver.page_source
soup = bs(html, 'html.parser')
itemlist = soup.findAll('div',{"class": "section--itemcard"})
time.sleep(5)

# 가져온 상품리스트에서 필요한 상품명, 가격, 상품링크를 출력 !!
for item in itemlist :
    title = item.find("span", {"class": "text--title"}).text
    price = item.find("strong", {"class": "text--price_seller"}).text
    link = item.find("span", {"class": "text--itemcard_title ellipsis"}).a['href']

    print("상품명   : ", title)
    print("가격    : ", price)
    print("상품링크 : ",  link)

time.sleep(3)
driver.close()

사이사이에 sleep()을 해주는 이유는 크롤링할 때 차단을 막기위함. 마치 실제 사용자가 사용하는 것 처럼 보이기 위함임.

우리나라 사이트는 크롤링이 막혀있는데가 많던데, 구글은 또 신기하게 안막혀있었음. 구글에서 이미지 크롤링도 이 코드를 활용하면 똑같이 할 수 있었음.

profile
어제보다 낫은 오늘, 오늘보다 낫은 내일

0개의 댓글