python/웹크롤링

[Python] selenium - 웹페이지 html 가져오기

wjwkddyd221001 2022. 12. 11. 01:23

동적 웹페이지가 로딩이 완료된 경우

동적페이지가 모두 로딩이 완료된 후, 페이지의 HTML을 파싱하는 방법은 두 가지가 있다.

  1. selenium의 By를 이용해 element 찾기
  2. bs4를 이용해 HTML문자열 파싱하기

페이지가 계속 변하지 않는 경우, bs4를 이용한 두 번째 방법이 더욱 속도가 빠르다.

 

1. selenium의 By를 이용해 element 찾기

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.find_element(By.CSS_SELECTOR, "").text

 

2. bs4를 이용해 HTML문자열 파싱하기

from bs4 import BeautifulSoup
from selenium import webdriver

soup = BeautifulSoup(driver.page_source, "html.parser")

# 1
soup.find()
soup.find_all() # 리스트 형태로 반환

# 2
soup.select_one()
soup.select # 리스트 형태로 반환

.get_text() 또는 .text를 이용해 텍스트만 추출할 수 있다.

 

참고자료

https://velog.io/@fhdufhdu/SIG-프로젝트-2.-Selenium과-BS4를-사용해보자데이터-수집