2
2

More than 1 year has passed since last update.

Selenium でループを書いたときの stale element reference: element is not attached to the page document エラー回避備忘録

Last updated at Posted at 2022-12-16

概要

久しぶりにSelenium を使ったら、
ループ処理のところで

stale element reference: element is not attached to the page document

といういうエラーに遭遇し、少しだけ詰まったので備忘録として残しておきます。

問題となったコード

汚いコードなのは許してください。。

test.py

divEl = driver.find_element_by_class_name("htBlock-adjastableTableF_inner")
tableElem = divEl.find_elements(By.TAG_NAME, "table")
tbodys = tableElem[0].find_elements(By.TAG_NAME, "tbody")
trs = tbodys[0].find_elements(By.TAG_NAME, "tr")

for i in range(len(trs)):
    tmp1 = trs[i].find_element_by_class_name("htBlock-adjastableTableF_actionRow")  # td

このループにおいて、0回目のループでは問題なく

tmp1 = trs[i].find_element_by_class_name("htBlock-adjastableTableF_actionRow")  # td

が行えていたのに対し、1回目のループでタイトルのエラーとなっていました。

解決策

test.py
divEl = driver.find_element_by_class_name("htBlock-adjastableTableF_inner")
tableElem = divEl.find_elements(By.TAG_NAME, "table")
tbodys = tableElem[0].find_elements(By.TAG_NAME, "tbody")
trs = tbodys[0].find_elements(By.TAG_NAME, "tr")

for i in range(len(trs)):
    divEl = driver.find_element_by_class_name("htBlock-adjastableTableF_inner")
    tableElem = divEl.find_elements(By.TAG_NAME, "table")
    tbodys = tableElem[0].find_elements(By.TAG_NAME, "tbody")
    trs = tbodys[0].find_elements(By.TAG_NAME, "tr")
    tmp1 = trs[i].find_element_by_class_name("htBlock-adjastableTableF_actionRow")  # td

ループの中でページ内のDOM情報を再度取得するように書くと、問題なくプログラムが実行されました。

以上。

2
2
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
2
2