Data Science

데이터 크롤링

봄프로 2023. 7. 15. 09:38
  • BeautifulSoup: python으로 html을 다루는 라이브러리
  • request: 페이지 요청 라이브러리
# 1. 스크래핑 페이지 지정
# 2. 페이지 요청
# 3. text를 html 형태로 변환
# 4. 태그값으로 원하는 데이터 추출
link = 'https://search.naver.com'
url = requests.get(link)
BeautifulSoup(url.text)
html.find('span', attrs = {'class': 'value'})

 

# 1. 웹 브라우저 창 열기
# 2. 지정한 페이지 불러오기
# 3. 창이 열릴 때까지 10초 대기
# 4. html 형태로 변환
# 5. 원하는 태그 값 가져오기
# 6. 웹 브라우저 창 닫기
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://search.naver.com')
driver.implicitly_wait(10)
html = BeautifulSoup(driver.page_source)
html.find('table', class_ = 'type_2')
driver.close()
  • 같은 페이지 내에서 행동을 해도 url 변하지 않는 경우 동적 크롤링 Selenium 사용하는 것이 바람직함
# 라이브러리
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

# 웹 페이지
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://www.naver.com')
driver.implicitly_wait(10)
time.sleep(1)

# 검색어 입력 후 엔터
a = driver.find_element(By.ID, 'query')  # 검색어 창
a.send_keys('검색어')                      # 검색어 입력
time.sleep(1)                            # 시간
a.send_keys(Keys.RETURN)                 # 엔터

# 버튼 클릭
driver.find_element(By.CLASS_NAME, 'popupCloseBtn.is-bottomBtn').click()

# find_element: 태그에 해당하는 값 가져오기
# find_elements: 태그에 해당하는 값 모두 가져오기
driver.find_elements(By.CLASS_NAME, 'bbsItem')