【Python】スクレイピング エラー

Uncategorized
159 words

久しぶりに Selenium のスクレイピングをしようと思ったら、エラーで動かなくなったのでその対処法。

環境

  • Windows 11 Home 21H2
  • Python 3.10.1
  • Selenium 4.4.3

エラー

XPath を指定してエレメントを取得しようとしたら、次のエラーが発生。

1
'WebDriver' object has no attribute 'find_element_by_xpath'

原因

Selenium 4.3.0 で削除されていた。

https://github.com/SeleniumHQ/selenium/blob/trunk/py/CHANGES#L24

1
2
Deprecated find_element_by_* and find_elements_by_* are now removed
SeleniumHQ/selenium: A browser automation framework and ecosystem.

解決方法

Selenium 4.3.0 以降は次のコードを使う。

1
2
3
4
5
6
7
8
9
10
11
12
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()