簡體   English   中英

消息:陳舊元素引用:元素未附加到頁面文檔PYTHON硒

[英]Message: stale element reference: element is not attached to the page document PYTHON selenium

我正在嘗試從網站獲取劇集鏈接。 所以我需要輸入鏈接並從情節中獲取信息。 它以2-3集的形式工作,然后崩潰,並在底部產生錯誤。 我試圖增加睡眠時間,但它仍然崩潰。

錯誤:

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

 import time import datetime import random import string import json import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from urllib.request import urlopen import urllib.request def send_imdb(id): try: r = requests.get('http://sdarot.bnlstudio.com/import.php?id=%s' % (id)) json = r.json() if json['status'] == "success": return json['id'] except: return("Err") links = [] seasons = [] link = "http://www.tvil.me/" chrome_options = Options() chrome_options.add_extension('gighmmpiobklfepjocnamgkkbiglidom.crx') driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(link) #Getting Posts links and split them page_right = driver.find_element_by_id("page-right") posts = page_right.find_elements_by_xpath("//div[@class='index-episode-caption']/a") for element in posts: href = element.get_attribute("href") splited = href.split("/") url = "%s//%s/view/%s/1/1/v/%s" % (splited[0], splited[2], splited[4], splited[8]) links.append(url) ##print(url) #Entering posts and gets IMDB ID E = 0; for link in links: driver.get(link) time.sleep(2) imdb_q = driver.find_element_by_xpath("//div[@id='view-trailer-imdb']/a") imdb = imdb_q.get_attribute("href") imdb_id = imdb.split("/")[4] post_id = send_imdb(imdb_id) print("Post_ID: %s" % (post_id)) seasons_num = driver.find_elements_by_xpath("//*[contains(@id, 'change-season-')]/a") total_seasons_num = len(seasons_num) for i in range(1, total_seasons_num): print("Season: %i" % (i)) season = driver.find_element_by_css_selector("#change-season-{num} a".format(num=i)) season.click() episodes = driver.find_elements_by_xpath("//*[contains(@id, 'change-episode-')]/a") for episode in episodes: E += 1 print("Episode: %i" % (E)) time.sleep(3) episode.click() # Break point time.sleep(3) 

當元素未附加到DOM時,將發生陳舊的元素異常。 過期的元素異常后,嘗試再次查找該元素。

考慮單擊元素將刷新頁面。
例:

 WebElement element = driver.findElement(By.Id("refreshButton"));
 element.Click(); //page will be refreshed after clicking this button
 element.Click(); //stale element exception will throw

現在,如果您對該元素執行任何操作(單擊,senkeys等),它將拋出StaleElementException,因為它丟失了引用(頁面已刷新)

為了解決這個問題,請在頁面刷新后再次找到該元素。

 WebElement element = driver.findElement(By.Id("refreshButton"));
 element.Click(); //page will be refreshed after clicking this button

 element = driver.findElement(By.Id("refreshButton"));
 element.Click();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM