일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- wordcloud
- selenium
- 웹크롤링
- Cosine-similarity
- 알고리즘
- recommendation system
- 협업 필터링
- TF-IDF
- coursera
- Tensor
- 부스트캠프
- 웹스크래핑
- 코테
- 백준
- 파이썬
- 데이터 엔지니어링
- SGD
- codingtest
- 딥러닝
- Python
- 머신러닝
- 시각화
- pytorch
- 추천 시스템
- 데이터
- 코딩테스트
- 프로그래머스
- Overfitting
- 추천시스템
- 분산 시스템
- Today
- Total
개발자식
[크롤링] Selenium_파파고 본문
이번에는 파파고로 진행을 해보자
from webdriver_manager.chrome import ChromeDriverManager # 자동으로 크롬드라이버(가상브라우저) 파일을 다운로드해주는 라이브러리
from selenium.webdriver.chrome.service import Service # 다운로드된 크롬드라이버 파일을 연결하기 위해 활용
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time
import pandas as pd
import warnings
warnings.filterwarnings("ignore") # 불필요한 Warning 메시지를 꺼줍니다.
파파고는 구글 번역기와 달리 id를 이용하기 깔끔하다.
#가상 브라우저 url 열기
translate_url = 'https://papago.naver.com/?sk=ko&tk=en' # sk=ko : Korean & tk=en : English
driver.get(translate_url)
#id가 txtSource인 곳에 번역할 문장을 보낸다.
driver.find_element_by_id('txtSource').send_keys('파이썬은 쉽습니다.') # Send_keys
#id가 txtTarget인 곳에서 text를 가져온다.
translated_contents = driver.find_element_by_id('txtTarget')
print(translated_contents.text)
#가상 브라우저 닫기
driver.close()
driver.quit()
결과 :
Python is easy.
구글 번역기와 같이 기사 본문 단어 (빈도가 높은 상위 100개)를 번역해보자.
파파고 번역 웹사이트의 경우 번역 키워드 입력 후 번역된 결과가 노출될 때까지의 간격이 길다.
일정 시간 (ex 3초)으로 지정해 기다릴 경우 종종 번역이 채 끝나지 않은 상태에서 잘못된 번역 결과를 가져오게 된다.
번역이 성공적으로 종료된 시점에만 나타나는 어떠한 태그가 있을 경우,
우리는 이 태그가 눈앞에 나타날 때까지 대기하여 (일정 시간 3초 대신) 번역 완료 시 때까지 유동적으로 기다릴 수 있다.
위의 사진에서 번역이 완료될 경우 나타나는 발음이 담긴 태그 ("diction_~" class를 가진 p 태그)가 바로 그 태그이다.
실제로 이 p 태그는 번역이 완료되면 잠시 나타났다 사라집니다.
-> 이 태그의 로딩이 완료될 때까지 기다린 후 번역 결과를 가져오자
참고:
실행 코드 :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
translation_result_papago = {}
service = Service(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
translate_url = 'https://papago.naver.com/?sk=ko&tk=en'
driver.get(translate_url)
print(driver.current_url)
time.sleep(3)
for key in translation_target: # 상위 100번째 빈도수에 해당하는 단어까지 담겨있는 dict
driver.find_element_by_id('txtSource').clear()
driver.find_element_by_id('txtSource').send_keys(key)
time.sleep(3) # 네트워크의 속도에 따라 잠깐씩 쉬어주면서 진행합니다.
wait = WebDriverWait(driver, timeout=10) # timeout : 지정한 조건의 충족까지 대기할 최대 시간 (만약 10초 내에 충족되지 않으면 에러가 발생)
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "#targetEditArea > p")))
translated_contents = driver.find_element_by_id('txtTarget').text
translation_result_papago[translated_contents] = translation_target[key] # 번역이 완료된 단어 dict의 value로 기존 dict의 value를 꽂아줍니다.
print('단어 {}의 번역 완료 : {}'.format(key, translated_contents))
print('전체 번역이 끝났습니다!')
driver.close()
driver.quit()
WebDriverWait : 교통정리 역할, 지정한 조건의 충족까지 대기할 최대 시간을 10초로 설정한다, 10초 내에 충족하지 못하면 실패를 반환한다.
wait.until(~) : ~조건을 충족 시킬 때까지, 위 CSS Selector로 지정한 Tag의 존재가 포착될 때까지 대기 후 아래 코드를 실행
-> id가 targetEditArea인 p 태그 element가 나올 때까지 최대 10초 기다린다.
참고 자료 : https://j.mp/3mCnc5G
selenium.webdriver.support.expected_conditions — Selenium 4.1.0 documentation
An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same)
www.selenium.dev
결과 :
'Data > Python' 카테고리의 다른 글
[크롤링] Post request 기반의 웹사이트 크롤링 (0) | 2022.03.30 |
---|---|
[크롤링] BeautifulSoup, Wadis 마감 상품 재고 체크 & 메일 발송 크롤링 (0) | 2022.03.30 |
[크롤링] Selenium_구글 번역기 (0) | 2022.03.29 |
[스크래핑] Web scraping for news articles (3) (0) | 2022.03.29 |
[스크래핑] Web scraping for news articles (2) (0) | 2022.03.28 |