GVKun编程网logo

StaleElementReferenceException: element is not attached to the page document while selecting the options from multiple Dropdowns using Selenium Python

20

本文将介绍StaleElementReferenceException:elementisnotattachedtothepagedocumentwhileselectingtheoptionsfro

本文将介绍StaleElementReferenceException: element is not attached to the page document while selecting the options from multiple Dropdowns using Selenium Python的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于'UnexpectedTagNameException' and Element should have been “select” but was“div” error using 'Select' function through Selenium java、ElementNotVisibleException:Selenium Python、frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException、How to avoid “StaleElementReferenceException” in Selenium?的知识。

本文目录一览:

StaleElementReferenceException: element is not attached to the page document while selecting the options from multiple Dropdowns using Selenium Python

Code trial:

#coding=utf-8from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import Select, WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport timeimport pandas as pd# Below is to crawl data from a webpage with two different dropdowntry:    driver = webdriver.Chrome(''./chromedriver'')    driver.get(''https://price.joinsland.joins.com/theme/index_theme.asp?sisaegbn=T05'')    select1 = Select(WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//select[@name=''sido'']"))))    for item1 in select1.options:        item1.click()        select2 = Select(WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//select[@name=''gugun'']"))))        for item2 in select2.options:            item2.click()            time.sleep(2)            # below is to get the attained date into excel file            table = driver.find_element_by_class_name(''tbl_box'')            tbody = table.find_element_by_tag_name(''tbody'')            rows=tbody.find_elements_by_tag_name(''tr'')            total = []            result = []            for index, value in enumerate(rows):                body = value.find_elements_by_tag_name(''td'')                for i in range(len(body)):                    data = body[i].text                    result.append(data)            total.append(result)            result=[]        df = pd.DataFrame.from_records(total)        df.to_excel(''text.xlsx'')except Exception as e:    print(e)finally:    driver.quit()

I have edited this code thanks to the lovely comment below but I get the same
error saying as below.:

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

I roughly understand why this message shows up but still have no clear idea on
how to fix this. I would deeply appreciate any comment! Many thanks in
advance!

enter image descriptionhere

答案1

小编典典

This is what I figured out. But I’m not sure if code is right or not. I don’t
know python.

#get selectselect1 = Select(driver.find_element_by_xpath(''//select[@name="sido"]''))#get all options from selectoptions1 = select1.optionsfor opt1 is options1:    #select the option which has the value of opt1    select1.select_by_value(opt1.get_attribute("value"))    time.sleep(5)    select2 = Select(driver.find_element_by_xpath(''//select[@name="gugu"]''))    options2 = select2.options    for opt2 in options2:        select1.select_by_value(opt2.get_attribute("value"))        time.sleep(4)

'UnexpectedTagNameException' and Element should have been “select” but was“div” error using 'Select' function through Selenium java

'UnexpectedTagNameException' and Element should have been “select” but was“div” error using 'Select' function through Selenium java

如何解决''UnexpectedTagNameException'' and Element should have been “select” but was“div” error using ''Select'' function through Selenium java?

This error message…

''UnexpectedTagNameException'' : Element should have been "select" but was "div"

…暗示您已使用Select类与元素进行交互,其中元素为<div>

click()在文本上具有借入能力的元素上,可以使用以下定位策略:

  • xpath:
        new webdriverwait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h4[@bta-description'' and text()=''Our calculators'']//following::div[@bta-select-table row'']//b[@button'']"))).click();
        new webdriverwait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@selectric-items'']//li[contains(., ''Borrowing Capacity'')]"))).click();

解决方法

在这种形式的下拉列表中,选择不起作用。

我为此写代码

    public static void main(String[] args) throws InterruptedException 
    {
    WebDriver driver =new ChromeDriver();
    //driver.manage().window().maximize();
    driver.get("http://www.ia.ca/");
    Thread.sleep(3000);
    driver.findElement(By.xpath("//*[@id=\"nav-secondaire\"]/div[1]/ul/li[4]/a")).click();
    driver.findElement(By.xpath("//*[@id=\"nav-secondaire\"]/div[1]/ul/li[4]/ul/li[1]/section/ul/li[1]/a")).click();

   //DropDown code
    WebElement selectMyElement =driver.findElement(By.xpath("//*[@id=\"grille-zone-cta\"]/div/div/div/div/div/div[2]/div[1]"));
    Select cal = new Select(selectMyElement);
    cal.selectByIndex(1);

它给了我例外

‘UnexpectedTagNameException’

错误消息是

元素应为“选择”但为“ div”

ElementNotVisibleException:Selenium Python

ElementNotVisibleException:Selenium Python

我已经检查了所有以前的类似问题,它们不适用于我的情况。

       try:          element = wait.until(          EC.presence_of_element_located((By.XPATH, "//*[@id=''_ariaId_73.folder''] | //*[@id=''_ariaId_133.folder'']"))       )       except:           print "403 : Monitoring Not Found"    element.click()

它是不会进入异常块还可以,但它仍然抛出ElementNotVisibleExceptionelement.click()方法。

答案1

小编典典

关于解决方案的几句话:

  1. 与预期子句的条件presence_of_element_located()涉及 用于检查的元件是存在于页面的DOM的期望。 这并不一定意味着该元素是可见的。一旦找到元素,用于查找元素的定位器将返回WebElement。因此,我们必须更改与 期望 相关的子句,presence_of_element_located()检查用于检查已知在页面DOM中存在的元素是否可见。 可见性意味着不仅显示元素,而且其高度和宽度都大于0。element是WebElement在可见时返回(相同)WebElementvisibility_of_element_located() __
  2. 展望未来,您已经尝试click()WebElement 调用方法。因此,代替presence_of_element_located()我们将使用该 element_to_be_clickable() 子句。
  3. 这是您自己的代码,做了一些小的更改:
        try:        element = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id=''_ariaId_73.folder''] | //*[@id=''_ariaId_133.folder'']")))    except:         print "403 : Monitoring Not Found"    element.click()

frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException

frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException

代替那些较小的冗余步骤,您可以切换到所需的 <iframe> 诱导 WebDriverWait 使用 xpath 优化如下:

new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("xpIframe")));

参考

您可以在以下位置找到一些相关讨论:

  • Ways to deal with #document under iframe
  • Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?
,

第 3 行

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath(xpIframe)));

您已经切换到 iframe。所以不需要第 4 行——它只是尝试切换到同一帧。尽量去掉(第2行也是多余的)

How to avoid “StaleElementReferenceException” in Selenium?

How to avoid “StaleElementReferenceException” in Selenium?

我正在使用Java实现许多Selenium测试。有时,我的测试由于导致失败StaleElementReferenceException。你能否提出一些使测试更稳定的方法?

答案1

小编典典

如果页面上发生的DOM操作暂时导致该元素不可访问,则会发生这种情况。为了允许这些情况,您可以尝试在最终引发异常之前循环访问几次元素。

试试darrelgrainger.blogspot.com的出色解决方案:

public boolean retryingFindClick(By by) {    boolean result = false;    int attempts = 0;    while(attempts < 2) {        try {            driver.findElement(by).click();            result = true;            break;        } catch(StaleElementException e) {        }        attempts++;    }    return result;}

我们今天的关于StaleElementReferenceException: element is not attached to the page document while selecting the options from multiple Dropdowns using Selenium Python的分享已经告一段落,感谢您的关注,如果您想了解更多关于'UnexpectedTagNameException' and Element should have been “select” but was“div” error using 'Select' function through Selenium java、ElementNotVisibleException:Selenium Python、frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException、How to avoid “StaleElementReferenceException” in Selenium?的相关信息,请在本站查询。

本文标签: