python - Selenium使用時、例外処理用のlibraryをimportし、forループ中のエラーをtry/exceptで無視する
習慣化196日目
Seleniumで「複数のボタンを順番に押しておいて次へをクリックする」ということがしたい。
複数のボタンにはcss selector に通し番号が付いていて、それをforループで順番に押せば良いなと思い処理を書いた。
ただ、ページによってそのボタンが押せないようになっているところがあり「そんなボタンはないよ」というエラーになってしまった。
forループ中にエラーがあったときに、対象のエラーを無視する。
参考
Python - no such elementが出たときにページが移行できるプログラム|teratail
https://teratail.com/questions/226721
エラーになる箇所
for number in range(15): driver.find_element_by_css_selector("#target_bottun"+number).click()
対象のエラー
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#target_bottun3"} (Session info: chrome=87.0.4280.88)
対応
# 例外処理用のlibraryをimport from selenium.common.exceptions import NoSuchElementException for number in range(15): try: driver.find_element_by_css_selector("#target_bottun"+number).click() except NoSuchElementException: pass