久しぶりに Selenium のスクレイピングをしようと思ったら、エラーで動かなくなったのでその対処法。
環境
- Windows 11 Home 21H2
- Python 3.10.1
- Selenium 4.4.3
エラー
XPath を指定してエレメントを取得しようとしたら、次のエラーが発生。
'WebDriver' object has no attribute 'find_element_by_xpath'

原因
Selenium 4.3.0 で削除されていた。
selenium/CHANGES at trunk · SeleniumHQ/selenium
A browser automation framework and ecosystem. Contribute to SeleniumHQ/selenium development by creating an account on GitHub.
Deprecated find_element_by_* and find_elements_by_* are now removed
SeleniumHQ/selenium: A browser automation framework and ecosystem.
解決方法
Selenium 4.3.0 以降は次のコードを使う。
from selenium import webdriver # pip install selenium
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path="./chromedriver_105.0.5195.19.exe")
driver.implicitly_wait(20)
driver.get("https://www.yahoo.co.jp/")
driver.find_element(By.XPATH, '//*[@id="ContentWrapper"]/header/section[1]/div/form/fieldset/span/input')
driver.close()
driver.quit()