LoginSignup
2
4

More than 1 year has passed since last update.

Seleniumでループが上手く回らない時の対処法

Posted at

スクレイピングを実装していたらエラーメッセージが出た!

Seleniumをpythonを使用して実装していたら以下のようなエラーメッセージが表示された。
解決までに時間がかかってしまったので参考になればと思い投稿します。

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is
not attached to the page document

前提条件

Python 3.7.12
selenium
Chrome

手順

dockerで環境を用意

pythonで目的のサイトのスクレイピング処理を実装

それをループで処理する。

エラーの出たコード

sample.py
data = [1,2,3,4,5]
for i in data:
    driver.find_element_by_xpath("目的のxpath").click()
    driver.find_element_by_xpath("xpath").send_keys(i)

    driver.implicitly_wait(10) # 秒
    driver.find_element_by_xpath("xpath").click()  

    driver.implicitly_wait(10) # 秒
    driver.find_element_by_xpath("xpath").click()  

ループに成功したコード

sample.py
#追加
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

data = [1,2,3,4,5]
for i in data:
    driver.find_element_by_xpath("目的のxpath").click()
    driver.find_element_by_xpath("xpath").send_keys(i)

    #driver.implicitly_wait(10)
    element = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "xpath")))
    driver.find_element_by_xpath("xpath").click()  

    driver.implicitly_wait(10) 
    driver.find_element_by_xpath("xpath").click()  
    time.sleep(10)
ポイント

エラーの出たコードでも2回ほどループは成功していました。
element is not attached to the page documentのエラーメッセージが出た場合、エラーの出たページの要素を調べましょう。
もし要素と自分の記述したコードに差異がなければseleniumを安定動作させるようにコードを記述しましょう!

seleniumを安定動作させるために必要な待機処理

暗黙的な待機
driver.implicitly_wait()# 秒

このメソッドは
指定した要素が見つかるまでの待ち時間を設定出来ます

明示的な待機
WebDriverWait.until()

このメソッドは任意のhtmlが特定の状態になるまで待機します。
今回指定したvisibility_of_element_locatedは
ページ上の指定した要素が表示されるまで待機します。

time.sleep
time.sleep()# 秒

こちらはプログラムを一時停止するメソッドです。
ただしこちらのメソッドは停止したからといって必ずプログラムが動くというわけではありません。
最終手段として考えましょう。

ポイント

ループが正常に動かない場合暗黙的な待機を試してください。
それでも動かない場合には明示的な待機を
最終的にtime.sleepを使用してください。

参考

https://tanuhack.com/stable-selenium/
https://www.seleniumqref.com/api/python/time_set/Python_implicitly_wait.html

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