GVKun编程网logo

Selenium单击一次,但单击一次将返回StaleElementReferenceException(selenium 多次点击)

5

对于想了解Selenium单击一次,但单击一次将返回StaleElementReferenceException的读者,本文将提供新的信息,我们将详细介绍selenium多次点击,并且为您提供关于fr

对于想了解Selenium单击一次,但单击一次将返回StaleElementReferenceException的读者,本文将提供新的信息,我们将详细介绍selenium 多次点击,并且为您提供关于frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException、How to avoid “StaleElementReferenceException” in Selenium?、java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案、org.openqa.selenium.ElementNotInteractableException:尝试单击按钮时无法将元素滚动到视图中的有价值信息。

本文目录一览:

Selenium单击一次,但单击一次将返回StaleElementReferenceException(selenium 多次点击)

Selenium单击一次,但单击一次将返回StaleElementReferenceException(selenium 多次点击)

import sysimport urllib2import timefrom bs4 import BeautifulSoupfrom selenium import webdriverimport stringimport rereload(sys)sys.setdefaultencoding(''utf8'')baseUrl = ''https://www.breastsurgeons.org/new_layout/membership/membersearch/index.php''driver = webdriver.Chrome(''/usr/local/Cellar/chromedriver/2.36/bin/chromedriver'')driver.get(baseUrl)time.sleep(20)for p in range(1,282):    driver.find_element_by_xpath("//a[contains(text(),''>>'')]").click()    time.sleep(2)driver.quit()

打开baseUrl后,我手动单击同意,然后搜索要显示的医生列表。我想翻阅清单。现在,Selenium仅通过找到“

”来第一次单击。之后它停止并给出以下错误。

   driver.find_element_by_xpath("//a[contains(text(),''>>'')]").click()  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 80, in click    self._execute(Command.CLICK_ELEMENT)  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 628, in _execute    return self._parent.execute(command, params)  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 312, in execute    self.error_handler.check_response(response)  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 242, in check_response    raise exception_class(message, screen, stacktrace)selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

答案1

小编典典

错误说明了一切:

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

for()循环内的程序中,您将在页面上找到<a>文本标记为 > >*的tag元素并进行调用,click()并且由于 HTML DOM
发生更改而导致该click()事件。当您的程序第二次迭代循环时,也许未加载标识为的 WebElement ,但是 Selenium
尝试引用以前已经 过时的 迭代中的搜索。因此,您会看到 StaleElementReferenceExceptionfor()
driver.find_element_by_xpath("//a[contains(text(),''>>'')]") __
***

一种令人信服的迭代页面的方法是:

driver.find_element_by_xpath("//a[contains(text(),''>>'')]").click()

可以诱导WebDriverWait在-结合expected_conditions子句设置为element_to_be_clickable为
WebElement 与特定 页码 (例如 345 ,等)是 可点击 如下:

WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(text(),''3'')]"))).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?

如何解决How to avoid “StaleElementReferenceException” in Selenium??

如果页面上发生的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;
}

解决方法

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

java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案

java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案

因为页面内容有很多页,需要切换页数,但是切换跳转到第二页的时候,页面首先会自动刷新,导致出现如下异常:Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

	//获取当前页面的table内容
	static int count = 0;
	public static List getPageTableContent(WebDriver driver,WebElement table,String refreshElement ){
		
		//获取当前页面的table
//把下面这行代码的注释去掉即可
//		table= driver.findElement(By.xpath(refreshElement));
		
		List<WebElement> rows = table.findElements(By.tagName("tr"));//根据行标签,获取所有行对象
		//String[] tableTitle = {"编号","配置名称","首页返回按钮","首页banner显示","极简尾页",""};
		ArrayList<String> tableContent = new ArrayList<>();
		for(WebElement row:rows){//从所有行中遍历每一行
			List<WebElement> col = row.findElements(By.tagName("td"));//一行中,所有列标签,
			for(WebElement cell:col){//一行中,所有的列(也就是单元格)
				String content = cell.getText();//每个单元格的内容
				tableContent.add(content);
				//System.out.println(content + "...content");
				//System.out.println(driver.findElement(By.xpath("//td[contains(text(),''可以'')]")).getText() + "...findElement");
				
			}
		}
		return tableContent;
	}
	
	//获取总页数
	public static int getPageAllNo(WebDriver driver){
		//获取总页数
				String pageCountSumStr = driver.findElement(
						By.xpath("//*[@id=''product_mgt_wrap'']/div/div[2]/div[3]/table/tbody/tr/td[8]/span")).getText();
				int pageCountSum = Integer.parseInt(pageCountSumStr.substring(3));
				return pageCountSum;
	}
	
	//获取当前页数
	public static int getCurrentPageNo(WebDriver driver){
		String pageCountSumStr = driver.findElement(
				By.xpath("//*[@id=''product_mgt_wrap'']/div/div[2]/div[3]/table/tbody/tr/td[8]/span")).getText();
		//获取当前页面页数
				String pageSource = driver.getPageSource();//获取当前页的源文件
				String pageElement = "pagination-num\" type=\"text\" value=\"";//在源文件中查找含有该字段的位置
				int pageIndex = pageSource.indexOf(pageElement);//通过上面的字段位置,定位文本框中的当前页数
				//通过定位出来的位置,获取文本框中的值 
	}
	//根据表格单元个内容定位单元格所在行
	/**
	 * @author:苏一叶 email:by.su@qq.com
	 * 1.进来先获取页面的总页数
	 * 2.如果总页数大于1
	 * 3.把每一条记录所有字段和记录所在的当前页数存入json中,表头为Key,值为Value。
	 * #3.把每一条记录中除编号外的其他字段和记录所在的当前页数存入json中,编号作为Key,其他已经存入json作为Value存入HashMap中。
	 * 4.传入需要定位的字符串,根据字符在json中查找对应的页数,把所有含有该字符的记录存到
	 * @throws InterruptedException 
	 */
	public static void getRangeFromRows(WebDriver driver,String str) throws InterruptedException{
		int pageCountSum = getPageAllNo(driver);//获取总页数
		int currentPageCount = getCurrentPageNo(driver);//获取当前页数
		
		//需要定位元素的xpath
		String strContent = "//*[contains(text(),''" + str + "'')]";
		//获取当前页面的table
        String refreshElement = "//*[@id=''product_mgt_wrap'']/div[1]/div[2]/div[2]/div[2]/div[2]/table";
		WebElement table= driver.findElement(By.xpath(refreshElement));
		                                              
		if(pageCountSum == 1){
			ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,table,refreshElement);
			for(String content:tableContent){
				if(content.contains(str)){//若包含需要查找定位的关键字str
					driver.findElement(By.xpath(strContent)).click();
				}
			}
			
		}else{//页面总数大于1的时候
			boolean flag = false;//设置一个跳出的标志位
			for(int i=0;i<pageCountSum&&!flag;i++){
				//当前页面等于1的时候
				if(currentPageCount==1){
					ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,table,refreshElement);
					
					for(String content:tableContent){
						if(content.contains(str)){//若包含需要查找定位的关键字str
							driver.findElement(By.xpath(strContent)).click();
							flag = true;//若找到,即跳转出循环
							break;//退出该循环体
						}
					}
					Thread.sleep(1000);
					currentPageCount += 1;//设置页数为2,页数大于1,逻辑转到else下面的代码块
				}else{
					//点击下一页的按钮,页面跳转到下一页,从第1页跳转到第2页
					driver.findElement(By.xpath("//*[@id=''product_mgt_wrap'']/div/div[2]/div[3]/table/tbody/tr/td[10]/a/span/span[2]")).click();
					Thread.sleep(1500);
					//从第2页开始,每翻一页,都进行查找定位
					for(int n=2;n<=pageCountSum&&!flag;n++){
						ArrayList<String> tableContent = (ArrayList)getPageTableContent(driver,table);
						//点击下一页按钮
						driver.findElement(By.xpath("//*[@id=''product_mgt_wrap'']/div/div[2]/div[3]/table/tbody/tr/td[10]/a/span/span[2]")).click();
						Thread.sleep(1000);
						currentPageCount = getCurrentPageNo(driver);//获取跳转后的页数
						
						for(String content:tableContent){
							if(content.contains(str)){//若包含需要查找定位的关键字str
								driver.findElement(By.xpath(strContent)).click();
								flag = true;//找到定位跳转到flag标志位
							}
						}
						/*//获取所有页面的内容
						tableContentAll.addAll((ArrayList)getPageTableContent(driver,table,refreshElement));*/
					}
				}
			}
			Thread.sleep(1000);
		}
	}

参考自:

http://www.cnblogs.com/fengpingfan/p/4583325.html

http://stackoverflow.com/questions/28066135/org-openqa-selenium-staleelementreferenceexception-stale-element-reference-ele

org.openqa.selenium.ElementNotInteractableException:尝试单击按钮时无法将元素滚动到视图中

org.openqa.selenium.ElementNotInteractableException:尝试单击按钮时无法将元素滚动到视图中

我正在使用FF 60.0的壁虎驱动程序selenium java。以前我的代码运行正常,但是突然之间,现在每次运行它时,都会出现错误,就像could not be scrolled into view我尝试单击按钮时一样。下面是我的代码,我尝试Thread.sleep(5000)或隐式等待,但没有任何效果。我被卡在这里。

public void goToWorkerSummary() throws InterruptedException {
    WebElement btnWorkerSummary = driver.findElement(By.xpath("//a[@href='/admin/worker-summary']"));
    //Thread.sleep(5000);//wait.until(ExpectedConditions.visibilityOf(btnWorkerSummary).click();
    btnWorkerSummary.click();
}

至此的代码有效,但是一旦到达此处,它就会显示上述错误。下面是错误代码段。

Exception in thread "main" org.openqa.selenium.ElementNotInteractableException: Element <ahref="/admin/worker-summary"> could not be scrolled into view
Build info: version: '3.12.0',revision: '7c6e0b3',time: '2018-05-08T15:15:03.216Z'
System info: host: 'CPU-38',ip: '192.168.0.55',os.name: 'Windows 8',os.arch: 'x86',os.version: '6.2',java.version: '1.8.0_51'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities {acceptInsecureCerts: true,browserName: firefox,browserVersion: 60.0.2,javascriptEnabled: true,moz:accessibilityChecks: false,moz:headless: false,moz:processID: 2480,moz:profile: C:\Users\xyz\AppData\Lo...,moz:useNonSpecCompliantPointerOrigin: false,moz:webdriverClick: true,pageLoadStrategy: normal,platform: XP,platformName: XP,platformVersion: 6.2,rotatable: false,timeouts: {implicit: 0,pageLoad: 300000,script: 30000}}
Session ID: 08c08933-06f6-480c-88c9-9d7ab718c2c8
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:276)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:83)

关于Selenium单击一次,但单击一次将返回StaleElementReferenceExceptionselenium 多次点击的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于frameToBeAvailableAndSwitchToIt 之后的 Selenium StaleElementReferenceException、How to avoid “StaleElementReferenceException” in Selenium?、java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案、org.openqa.selenium.ElementNotInteractableException:尝试单击按钮时无法将元素滚动到视图中等相关内容,可以在本站寻找。

本文标签: