본문 바로가기
Python/Crawlling

[파이썬, Python] 셀레니움(Selenium) 라이브러리를 활용한 브라우저 컨트롤링

by coding-choonsik 2023. 9. 5.
728x90
반응형
SMALL

1. 셀레니움(Selenium)

  • 셀레니움은 브라우저를 컨트롤 할 수 있도록 지원하는 라이브러리
  • 주로 웹 애플리케이션의 테스트 자동화, 웹 스크래핑, 웹 애플리케이션의 상호 작용 및 데이터 수집을 위해 개발
!pip install selenium
!pip install chromedriver_autoinstaller

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.google.co.kr/')

search = driver.find_element('name', 'q')   # name이 q인 태그 하나를 찾음
from selenium.webdriver.common.keys import Keys  # 키보드의 키들을 컨트롤할 수 있는 라이브러리

search.send_keys('날씨')  # '날씨'라는 글자를 검색창에 쓰게함
search.send_keys(Keys.RETURN)   # Keys.RETURN: Enter

2. 네이버 웹툰 댓글 크롤링 

  • https://comic.naver.com/webtoon/detail?titleId=796152&no=49
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get('https://comic.naver.com/webtoon/detail?titleId=796152&no=49')

soup = BeautifulSoup(driver.page_source)

comment_area = soup.findAll('span',{'class','u_cbox_contents'})
print(comment_area)

 

print('-----------베스트 댓글------------')
for i in range(len(comment_area)):
    comment = comment_area[i].text.strip()
    print(comment)
    print('--------------------')

 

 

2-1. XPath

  • 선택된 element에서 오른쪽 마우스 -> copy -> copy full XPath
  • XPath: 기존의 컴퓨터 파일 시스템에서 사용하는 경로 표현식과 유사한 XML의 경로 언어
  • /html/body/div[1]/div[5]/div/div/div[4]/div[1]/div[3]/div/div/div[8]/a/span[1]
# '전체 댓글 더보기' 클릭하기
driver.find_element('xpath', '/html/body/div[1]/div[5]/div/div/div[4]/div[1]/div[3]/div/div/div[8]/a/span[1]').click()

soup = BeautifulSoup(driver.page_source)
comment_area = soup.findAll('span',{'class','u_cbox_contents'})
print(comment_area)

 

print('----------전체 댓글------------')
for i in range(len(comment_area)):
    comment = comment_area[i].text.strip()
    print(comment)
    print('--------------------')

 

 

728x90
반응형
LIST