Selenium과 BeautifulSoup를 함께 사용하기

서대철·2023년 8월 11일
0

동적 웹사이트와 같이 BeautifulSoup만을 사용해서는 접근 불가능한 컨텐츠가 있을 때가 꽤나 있다. 예를 들어, 특정 내용을 검색한 결과를 출력하는 창을 띄우기 위해 다음의 단계를 거쳐야 한다고 가정해보자:
1. 홈페이지에서 검색을 위한 아이콘을 클릭
2. 검색할 키워드 입력
3. 검색을 실행하기 위한 버튼 클릭

이런 경우에는 Selenium을 사용해서 먼저 필요한 페이지에 접근을 하고 BeautifulSoup의 파싱 기능을 사용하면 용이하게 작업이 가능하다.

# 모듈 임포트
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

# Chrome WebDriver 초기화
driver = webdriver.Chrome(executable_path='../driver/chromedriver')

# 사이트 접속
url = 'https://example.com'  # Replace with the actual URL
driver.get(url)

# 검색 창 클릭
magnifier_button = driver.find_element_by_id('magnifier-id')  # Replace with the actual ID
magnifier_button.click()

# 검색어 입력 후 엔터
search_input = driver.find_element_by_id('search-input-id')  # Replace with the actual ID
search_keyword = 'your search keyword'
search_input.send_keys(search_keyword)
search_input.send_keys(Keys.RETURN)

# 검색 결과 대기
driver.implicitly_wait(10)

# 검색 결과 창을 html로 추출
results_html = driver.page_source

# 창 종료
driver.quit()

이렇게 selenium을 활용해서 html을 추출해 내고 나서 BeautifulSoup를 이용할 수 있다.

# HTML 파싱
soup = BeautifulSoup(results_html, 'html.parser')

# 필요한 태그에 접근
result_items = soup.find_all('div', class_='result-item')

# 필요한 내용 출력
for item in result_items:
    print(item.get_text())

1개의 댓글

comment-user-thumbnail
2023년 8월 11일

많은 도움이 되었습니다, 감사합니다.

답글 달기