Computer Science/BackEnd

[에러 해결] AttributeError: WebDriver object has no atribute find_element_by_class

토마토. 2023. 3. 27. 12:58
page_num = 2
url = f"https://tomatolife.tistory.com/{page_num}"

driver = webdriver.Chrome(executable_path="chromedriver")
driver.get(url=url)

try:
    element = WebDriverWait(driver, 5).until(
        EC.presence_of_element_located((By.CLASS_NAME, "contents_style"))
    )
    search_box = driver.find_element_by_class_name("contents_style")
    print(search_box)
finally:
    driver.quit()

셀레니움에서 dwebdriver.find_element_by_class_name 함수를 사용하려고 했으나 아래와 같은 에러가 발생했다. 

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[10], line 11
      7 try:
      8     element = WebDriverWait(driver, 5).until(
      9         EC.presence_of_element_located((By.CLASS_NAME, "contents_style"))
     10     )
---> 11     search_box = driver.find_element_by_class_name("contents_style")
     12     print(search_box)
     13 finally:

AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'

 

해결 방법

selenium 4는 find_element_by... 시리즈를 find_element 함수로 통일했다. 

따라서 find_element_by_class_name이 아니라 find_element(By.CLASS_NAME, "class_name")으로 바꿔주면 해결된다. 

page_num = 2
url = f"https://tomatolife.tistory.com/{page_num}"

driver = webdriver.Chrome(executable_path="chromedriver")
driver.get(url=url)

try:
    element = WebDriverWait(driver, 5).until(
        EC.presence_of_element_located((By.CLASS_NAME, "contents_style"))
    )
    search_box = driver.find_element(By.CLASS_NAME, "contents_style")
    print(search_box)
finally:
    driver.quit()