GVKun编程网logo

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

14

对于org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie感兴趣的读者,本文将会是一篇不错的

对于org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于Chrome浏览器中的Selenium在线程“main”org.openqa.selenium.WebDriverException中显示异常:等待驱动程序服务器启动超时、java – 如何用selenium webdriver发送cookies?、java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案、java-org.openqa.selenium.UnsupportedCommandException:使用Selenium找不到变量资源的有用信息。

本文目录一览:

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

如何解决org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie?

此错误消息…

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

……意味着非法企图在与当前文档不同的域下设置cookie。

细节

具体根据HTML的生活标准规范一个Document Object可被归类为在以下情况下一个Cookie规避文档对象:

  • 没有的文件 。
  • URL方案不是网络方案的文档。

深潜

对于无效的cookie域,当您访问不喜欢cookie的文档(例如本地磁盘上的文件)时,可能会发生此错误。

举个例子:

  • 样例代码:
        from selenium import webdriver
    from selenium.common import exceptions

    session = webdriver.Firefox()
    session.get("file:///home/jdoe/document.html")
    try:
        foo_cookie = {"name": "foo", "value": "bar"}
        session.add_cookie(foo_cookie)
    except exceptions.InvalidCookieDomainException as e:
        print(e.message)
  • 控制台输出:
    InvalidCookieDomainException: Document is cookie-averse
    

如果您已存储来自域的example.comcookie, 通过webdriver会话将这些存储的cookie 推送到任何其他不同的域,例如example.edu。存储的Cookie只能在中使用example.com。此外,要在将来自动登录用户,您只需要存储一次Cookie,即用户登录后的时间。在添加Cookie之前,您需要浏览到收集Cookie的相同域。

例如,一旦用户在应用程序中登录,就可以存储cookie,如下所示:

    from selenium import webdriver
    import pickle

    driver = webdriver.Chrome()
    driver.get(''http://demo.guru99.com/test/cookie/selenium_aut.PHP'')
    driver.find_element_by_name("username").send_keys("abc123")
    driver.find_element_by_name("password").send_keys("123xyz")
    driver.find_element_by_name("submit").click()
# storing the cookies
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
driver.quit()

稍后,如果您希望用户自动登录,则需要先浏览到特定的域/ url,然后必须添加cookie,如下所示:

    from selenium import webdriver
    import pickle

    driver = webdriver.Chrome()
    driver.get(''http://demo.guru99.com/test/cookie/selenium_aut.PHP'')

    # loading the stored cookies
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        # adding the cookies to the session through webdriver instance
        driver.add_cookie(cookie)
    driver.get(''http://demo.guru99.com/test/cookie/selenium_cookie.PHP'')

解决方法

我正在尝试将Cookie推送到上一个会话存储的Selenium firefox webdriver,但出现错误:

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

我阅读了此HTML Standard
Cookie规章
,一点也不懂。

因此,问题是如何将cookie推送到上一个存储的webdriver会话中?

Chrome浏览器中的Selenium在线程“main”org.openqa.selenium.WebDriverException中显示异常:等待驱动程序服务器启动超时

Chrome浏览器中的Selenium在线程“main”org.openqa.selenium.WebDriverException中显示异常:等待驱动程序服务器启动超时

code is correct. added code for time out exception. implicitlyWait added
public class SeleniumClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","C:\\\\Drivers\\\\chromedriver.exe");
        //System.setProperty("webdriver.gecko.driver","F:/Selenium/Jars and Drivers/Drivers/Firefox/geckodriver-v0.29.0-win64/geckodriver.exe");
        WebDriver driver = new ChromeDriver();
        //WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        driver.get("http://www.google.com");
    }

}
,

https://sites.google.com/a/chromium.org/chromedriver/

尝试 - 我下载了最新的稳定版本并且它有效。

java – 如何用selenium webdriver发送cookies?

java – 如何用selenium webdriver发送cookies?

每次当我运行我的测试第一步是登录,而不是我到达页面.如果运行此测试通常登录操作需要很多时间.

如何通过登录操作?

使用Chrome和Firefox驱动,使用java语言.

解决方法

使用 Java API创建Cookie,如下所示:
Cookie ck = new Cookie("name","value");
driver.manage().addCookie(ck);

使用Python API创建Cookie如下:

driver.add_cookie({'name': 'foo','value': 'bar'})

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

java-org.openqa.selenium.UnsupportedCommandException:使用Selenium找不到变量资源

java-org.openqa.selenium.UnsupportedCommandException:使用Selenium找不到变量资源

我正在使用使用硒协议的phantomjs webdriver渲染网页.当我尝试渲染网页时,出现以下错误

RemoteWebDriver.get(url)

尽管我的webdriver正在运行.

我也尝试过重新启动phantomjs webdriver.

org.openqa.selenium.UnsupportedCommandException: Variable Resource Not Found - {"headers":{"Accept-Encoding":"gzip,deflate","Connection":"Keep-Alive","Content-Length":"39","Content-Type":"application/json; charset=utf-8","Host":"10.20.1.239:9517","User-Agent":"Apache-HttpClient/4.5.5 (Java/1.8.0_171)"},"httpVersion":"1.1","method":"POST","post":"{\"url\":\"http://example.com/\"}","url":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","urlParsed":{"anchor":"","query":"","file":"url","directory":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/","path":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","relative":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/session/07e53c90-6b45-11e9-892c-4faf7180871b/url","queryKey":{},"chunks":["session","07e53c90-6b45-11e9-892c-4faf7180871b","url"]}}
Command duration or timeout: 10.20 seconds
Build info: version: 'unkNown',revision: 'unkNown',time: 'unkNown'
System info: host: 'ip-10-20-1-73.ec2.internal',ip: '10.20.1.73',os.name: 'Linux',os.arch: 'amd64',os.version: '3.10.0-862.2.3.el7.x86_64',java.version: '1.8.0_171'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{applicationCacheEnabled=false,rotatable=false,handlesAlerts=false,databaseEnabled=false,version=2.1.1,platform=LINUX,browserConnectionEnabled=false,proxy=Proxy(direct),nativeEvents=true,acceptSslCerts=false,driverVersion=1.2.0,locationContextEnabled=false,webStorageEnabled=false,browserName=phantomjs,takesScreenshot=true,driverName=ghostdriver,javascriptEnabled=true,cssSelectorsEnabled=true}]
Session ID: 07e53c90-6b45-11e9-892c-4faf7180871b
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_171]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_171]
        at 
最佳答案
RemoteWebDriver是关键字/保留的单词.因此,RemoteWebDriver实例的名称应不同.此外,在调用RemoteWebDriver时,您需要传递Selenium Grid Hub的URL和DesiredCapabilities实例作为强制参数,并且可以使用以下(基于Windows)解决方案:

File path=new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path",path.getAbsolutePath());
DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
capabilities.setPlatform(Platform.XXX);         
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),capabilities);
driver.get("https://www.google.co.in");
System.out.println(driver.getTitle());
driver.quit();

关于org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Chrome浏览器中的Selenium在线程“main”org.openqa.selenium.WebDriverException中显示异常:等待驱动程序服务器启动超时、java – 如何用selenium webdriver发送cookies?、java+selenium报异常org.openqa.selenium.StaleElementReferenceException的解决方案、java-org.openqa.selenium.UnsupportedCommandException:使用Selenium找不到变量资源的相关信息,请在本站寻找。

本文标签: