언어/PYTHON

[Python 오류] TypeError: 'str' object is not callable | selenium 구글 검색 매크로 프로그램

만결숭이 2022. 8. 22. 15:37
반응형

__사건의 발단

팀장님이 selenium에 대해서 공부해오라고 하셨다.

유튜브를 따라 코드를 작성하던 도중에 오류가 남.

분명 치라는대로 똑같이 쳤고 오타도 없는데 왜 저 사람은 되고 나는 안 되지?

 

 

 

 

__오류 01 (AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'

Traceback (most recent call last):
   File "/Users/hanlim_air/HANLIM/python/selenium01.py", line 8, in <module>
       driver.find_element_by_css_selector('.gLFyf.gsfi').send_keys('파이썬')
AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'

 

내가 똑같이 입력한 유튜브의 코드(캡쳐) :

오른쪽 위 191010을 보니 2019년도에 만들어진 영상임에 틀림없다.

버젼 차이에 원인이 있을 거라는 직감이 든다.

 

 

 

 

 

__해결 01

 

 

selenium AttributeError 'Webdriver' object has no attribute 'find_element_by ... 에러

selenium AttributeError 'Webdriver' object has no attribute 'find_element_by ... 에러 글. 수알치 오상문 셀레니움 상위 버전(4)에서 나타나는 에러입니다. find_element_by...() 함수를 사용하지..

blog.daum.net

역시나 서치해보니 셀레니움 상위 버전에서 나타나는 에러라고 한다.

 

참고로 내 파이썬 버전 :

Python 3.10.6

 

그래서 이 블로거의 설명에 따르면,

 

 

1. 아래의 임포트를 추가한 뒤

from selenium.webdriver.common.by import By

 

2. 아래 내용대로 오류가 발생한 8, 9번째 줄을 바꾸었다.

셀레니움 3:

driver.find_elements_by_css_selector(".className")

셀레니움 4:

driver.findElements(By.cssSelector(".className"))

 

를 보고 내가 바꿨던 결과:

driver.findElement(By.cssSelector('.gLFyf.gsfi').send_keys('파이썬')
driver.findElement(By.cssSelector('.gLFyf.gsfi').send_keys(Keys.ENTER)

 

>> 근데 안 된다..

(미리 결론을 말하자면, 저 블로그에 정확하게 설명이 되어 있었는데 내가 잘못 이해하고 사용했던 것이었다.

심지어 파이썬이 아니라 자바에서 쓰이는 카멜 형태잖아,, 부끄)

반응형

 

 

 

 

__오류 02 (TypeError: 'str' object is not callable)

Traceback (most recent call last):
   File "/Users/hanlim_air/HANLIM/python/selenium01.py", line 9, in <module>
      driver.find_element(By.CSS_SELECTOR('.gLFyf.gsfi')).send_keys('파이썬')
TypeError: 'str' object is not callable

이리저리 자동완성을 따라 바꿔보아도 똑같은 오류가 계속 뜬다.

 

 

 

__해결 02

driver.find_element(By.CSS_SELECTOR, '.gLFyf.gsfi').send_keys('파이썬')
driver.find_element(By.CSS_SELECTOR, '.gLFyf.gsfi').send_keys(Keys.ENTER)

서치해서 찾아 낸 제대로 된 형태 !

 

쒸익쒸익 하며 위의 블로그를 다시 정독해보니

다음 예제처럼 사용합니다.
 
elem = driver.find_element(By.NAME, "q")
title = driver.find_element(By.XPATH, r'//*[@id="bestList"]/ol/li[1]/p[1]').text
driver.find_element(By.XPATH, r'//*[@id="divYes24SCMEvent"]/div[2]/div[2]/a').click()

이렇게 정확하게 쓰여 있었다.

결론은 내가 글을 제대로 안 본 거였음.

 

 

 

 

 

__결과:구글 검색 매크로 프로그램

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


driver = webdriver.Chrome('./chromedriver')
url = 'https://google.com'
driver.get(url)

driver.find_element(By.CSS_SELECTOR, '.gLFyf.gsfi').send_keys('파이썬')
driver.find_element(By.CSS_SELECTOR, '.gLFyf.gsfi').send_keys(Keys.ENTER)

그리하여 여기까지 완성된 구글 검색 매크로 프로그램.

구글을 켜서, '파이썬'을 검색하고, 엔터까지 쳐 준다.

 

금방 해결할 수 있었을텐데 시간을 많이 쓰게 되어 분하지만, 잘 작동되니 기분이 좋다.

파이썬 완전 재미있슴 !

반응형