SeleniumのAttributeError: object has no attribute 'find_element_by_id' を解決する

本ページはプロモーションが含まれています

Seleniumを使用してログインが必要なウェブサイトを操作する際、find_element_by_関連のエラーが発生することがあります。

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

このエラーの原因はseleniumのバージョンが4.3.0 以降でfind_element_by_の使用方法が変更されたためです

finf_element_by_name           4.3.0より前
find_element(By.ID, "xxx")       4.3.0以降

Byをimportして使用します
from selenium.webdriver.common.by import By

以下では、Selenium 4.3.0以降での解決策を紹介します。Google Colaboratoryでも動作します。

対応策

Seleniumのバージョンを下げる。これも解決策ですが、続いてSelenium 4.3.0以降での解決方法について説明します。

# Seleniumのバージョンを下げる
$ pip install selenium==4.0.0

selenium 4.3.0以降の解決方法

入力フォームなどの要素を確認して下さい。Google ColaboratoryでもWorkします。

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

ID = "yourID"
password = "yourpassword" 

#ログイン情報入力
id = driver.find_element(By.ID, "user_session_email")
id.send_keys(ID)

#パスワード入力
password_input = driver.find_element(By.ID,  "user_session_password")
password_input.send_keys(password)

#ログイン、クリック
login = driver.find_element(By.CSS_SELECTOR, "input.fade.commit")
login.click()

find_element_by_の代わりにfind_element(By.ID, "xxx")といった形式を使用することで、AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'などのエラーを回避できます。

関連記事

  • この記事を書いた人

drーharv

こんにちは、Dr. Harv です。専門医としてのキャリアを積む一方で、資産運用、副業、ポイ活にも取り組んでいます。 このブログ「dr-harv.com」では、日々の日常、投資の知見、趣味など幅広いトピックを扱っています。より良い未来につながることをコンセプトにしています。読者の皆様にとって何か役立つ情報を提供できれば幸甚です。

-Python