[Daily Post]는 매일매일 탐구한 내용을 간략하게 기록하는 포스트입니다.
따라서 정리되지 않은 내용과 추측을 포함하고 있을 수 있습니다.
더 체계적인 형식을 갖춘 글은 해당 카테고리의 포스트를 확인해주세요 :)

Daily Study

Selenium

  • 학교에서 단순 반복작업을 할 일이 생겼는데, selenium을 활용하면 좋을 것 같다.
  • selenium 사용 경험은 전무. python 프로젝트도 전무. 오늘을 첫걸음으로 생각하면 된다.
  • excel에 있는 문자열을 검색하고, url을 타고 들어가서 검색 결과를 output으로 받는 것

오늘의 시행착오

Selenium Attribute Error

from selenium import webdriver
###from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option('detach',True)

driver = webdriver.Chrome('/opt/homebrew/bin/chromedriver',options=options)
driver.get("https://www.google.com/")

##driver.find_element(By.ID).send_keys('hi')
  1. 위의 코드는 구글 홈페이지를 driver로 설정하고, 창을 열어놓은 뒤 옵션에 따라 detach를 유지하는 코드이다.
  2. 근데 나는 여기에 덧붙여서 주석처리 된 코드의 주석을 지우고, element에 접근을 하고 싶어서 다음과 같은 방식을 사용했다.
  • 옛날 API를 따라 find_element_by_id로 접근
  • 최근 API를 따라 find_element(By.ID)로 접근

두 방법을 모두 사용했는데 Attribute Error를 출력할 뿐이었다.
이 정도로 간단한 코드를 작성하다 생기는 에러는 간단한 에러이니만큼 구글링하면 사례가 많이 나오던데, 어째서인지 비슷한 사례조차 잘 안 보이는 것 같다. 일 조금 편하게 해보려고 가벼운 마음으로 시작한건데 처음 배우는 도구이니만큼 시행착오가 상당하다.

마음은 울고 있지만 누구보다 태연한 표정으로 Selenium Documentation을 참조했다.
Webdriver에서 Elements로 찾아가면 되는 것이 뻔했으나 초심자니까 Webdriver를 먼저 읽었다.
문서를 읽고, 다시 코드를 고쳐서 얻어낸 결과는 다음과 같다.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option('detach',True)

driver = webdriver.Chrome('/opt/homebrew/bin/chromedriver',options=options)
driver.get("https://www.google.com/")

elem = driver.find_element(By.NAME,'q')
elem.send_keys('hi' + Keys.ENTER)
  1. Keys.ENTER를 쓰려면 Keys를 import 해야함
  2. elem 이라는 변수를 설정해서 driver의 find element 결과값을 넣고, 그 element에 send_keys를 별도로 실행