0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SeleniumでXpathを複数候補がある場合について

Last updated at Posted at 2023-04-09

何があったか

とあるサイトをスクレイピングしている際に若干Xpathが変わることがありました。
その際、例外処理で対応したので備忘録になります。

実際のコード

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

driver_path = "./chromedriver.exe"
chrome_service = service.Service(executable_path=driver_path)
driver = webdriver.Chrome(service=chrome_service)

xpath_list = []  # Xpathのリスト
for xpath in xpath_list:
    try:
        driver.find_element(by=By.XPATH, value=xpath).click()
        break
    except NoSuchElementException:
        pass

工夫点

Xpathの候補を事前に入れておくことによって、候補の数を自動で試す。
→候補が単体でも使用可能なので、関数化することによりコード全体をスッキリさせることも可能かと思います!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?