51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 2124|回复: 1
打印 上一主题 下一主题

selenium+java,读取文件添加到cookie失败,org.openqa.selenium.InvalidCookieDoma...

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2017-11-28 14:48:04 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
selenium+java,读取文件添加到cookie失败,org.openqa.selenium.InvalidCookieDomainExcepti
  1. /输入账号、密码登录网站,保存cookie到本地文件
  2. public static void saveCookie1(WebDriver driver) {
  3. // 打开百度网址
  4. driver.get("http://www.baidu.com");
  5. WebElement loginEntry = driver.findElement(By
  6. .xpath("//*[@id=\"u1\"]/a[7]"));
  7. loginEntry.click();

  8. //查找登录窗口
  9. Set<String> windowIds = driver.getWindowHandles();
  10. for (String windowId : windowIds) {
  11. if (driver.switchTo().window(windowId).getPageSource()
  12. .contains("下次自动登录")) {
  13. driver.switchTo().window(windowId);
  14. break;
  15. }
  16. }

  17. //等待WebElement元素加载
  18. WebElement userName = new WebDriverWait(driver, 10)
  19. .until(ExpectedConditions.presenceOfElementLocated(By
  20. .xpath("//*[@id=\"TANGRAM__PSP_8__userName\"]")));

  21. // 输入登录信息
  22. // WebElement userName = driver.
  23. // findElement(By.xpath("//*[@id=\"TANGRAM__PSP_8__userName\"]"));
  24. userName.sendKeys("1367115143@qq.com");

  25. WebElement passWord = driver.findElement(By
  26. .xpath("//*[@id=\"TANGRAM__PSP_8__password\"]"));
  27. passWord.sendKeys("8766502292273");

  28. WebElement member = driver.findElement(By.name("memberPass"));

  29. // 记住密码
  30. if (!member.isSelected()) {
  31. member.click();
  32. }

  33. // 点击登录按钮
  34. WebElement loginButton = driver.findElement(By
  35. .xpath("//*[@id=\"TANGRAM__PSP_8__submit\"]"));
  36. loginButton.click();

  37. // 保存cookie到本地
  38. File cookieFile = new File("baidu.cookie.txt");
  39. try {
  40. cookieFile.delete();
  41. cookieFile.createNewFile();
  42. FileWriter fileWriter = new FileWriter(cookieFile);
  43. BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
  44. System.out.println("cookie大小:"+driver.manage().getCookies().size());
  45. for (Cookie cookie : driver.manage().getCookies()) {
  46. bufferedWriter.write(cookie.getName() + ";" + cookie.getValue()
  47. + ";" + cookie.getPath()+";"+cookie.getDomain()
  48. + ";" + cookie.getExpiry() +";"+cookie.isSecure());
  49. bufferedWriter.newLine();
  50. System.out.println(cookie.getName()+"保存成功");
  51. }

  52. bufferedWriter.flush();
  53. bufferedWriter.close();
  54. fileWriter.close();

  55. } catch (IOException e) {
  56. // TODO Auto-generated catch block
  57. e.printStackTrace();
  58. }
  59. }

  60. //从本地文件读取内容,添加到cookie中,实现打开网站时显示已登录
  61. public static void useCookie1(WebDriver driver){

  62. //读取cookie       
  63. try{
  64. File cookieFile = new File("baidu.cookie.txt");
  65. FileReader fr = new FileReader(cookieFile);
  66. BufferedReader br = new BufferedReader(fr);

  67. String line;
  68. int i=0;
  69. //按行读取
  70. while( (line = br.readLine()) != null ){
  71. i++;
  72. System.out.print("第"+i+"行:");
  73. StringTokenizer stringTokenizer = new StringTokenizer(line,";");
  74. //读取每行逗号间的内容
  75. while(stringTokenizer.hasMoreTokens()){
  76. String name = stringTokenizer.nextToken();
  77. System.out.print(name);
  78. String value = stringTokenizer.nextToken();
  79. System.out.print(value);
  80. String domain = stringTokenizer.nextToken();
  81. System.out.print(domain);
  82. String path = stringTokenizer.nextToken();
  83. System.out.print(path);
  84. //处理日期,将读取的字符串转化为Date格式
  85. Date expiry = null;       
  86. String dt = stringTokenizer.nextToken();

  87. if(! dt.equals("null") ){
  88. expiry = new Date(dt);
  89. }
  90. System.out.print(expiry);
  91. boolean isSecure = new Boolean(stringTokenizer.nextToken()).booleanValue();
  92. System.out.println(isSecure);

  93. //添加cookie到driver
  94. Cookie cookie = new Cookie(name,value,domain,path,expiry,isSecure);       
  95. driver.manage().addCookie(cookie);


  96. }
  97. }
  98. }catch(Exception e){
  99. System.out.println();
  100. e.printStackTrace();
  101. }


  102. try {
  103. Thread.sleep(5000);
  104. } catch (InterruptedException e) {
  105. // TODO Auto-generated catch block
  106. e.printStackTrace();
  107. }

  108. driver.get("http://www.baidu.com");
  109. }
  110. 执行到函数useCookie1(WebDriver driver)->driver.manage().addCookie(cookie);添加失败
  111. 报错:
  112. org.openqa.selenium.InvalidCookieDomainException: You may only set cookies for the current domain
  113. Command duration or timeout: 87 milliseconds
  114. Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:16:47'
  115. System info: host: 'PC', ip: '10.9.3.108', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
  116. Session ID: cbfec852-11db-4c71-97e8-a64a9ca8c4fc
  117. Driver info: org.openqa.selenium.firefox.FirefoxDriver
  118. Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=false, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=42.0}]
  119. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  120. at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
  121. at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
  122. at java.lang.reflect.Constructor.newInstance(Unknown Source)
  123. at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
  124. at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
  125. at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:605)
  126. at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions.addCookie(RemoteWebDriver.java:687)
  127. at cxl.selenium.fouth.UseCookie.useCookie2(UseCookie.java:69)
  128. at cxl.selenium.fouth.UseCookie.main(UseCookie.java:27)
  129. Caused by: org.openqa.selenium.InvalidCookieDomainException: You may only set cookies for the current domain
  130. Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:16:47'
  131. System info: host: 'PC', ip: '10.9.3.108', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
  132. Driver info: driver.version: unknown
  133. at <anonymous class>.FirefoxDriver.prototype.addCookie(file:///C:/Users/admin/AppData/Local/Temp/anonymous5087220180491392428webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10409)
  134. at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/admin/AppData/Local/Temp/anonymous5087220180491392428webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12282)
  135. at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/Users/admin/AppData/Local/Temp/anonymous5087220180491392428webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12287)
  136. at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/Users/admin/AppData/Local/Temp/anonymous5087220180491392428webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12229)
  137. 十二月 01, 2015 4:12:20 下午 org.openqa.selenium.os.UnixProcess$SeleniumWatchDog destroyHarder
  138. 信息: Command failed to close cleanly. Destroying forcefully (v2). org.openqa.selenium.os.UnixProcess$SeleniumWatchDog@1567904d
复制代码


分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

该用户从未签到

2#
发表于 2017-11-28 15:01:22 | 只看该作者
你要先搞清楚 浏览器在request添加cookie要跟当前请求的URL是一个域的 ,webdriver 实例化浏览器的时候 默认给浏览器的URL是:data:.  所以你添加的cookie的域和当前URL不是一个域名下的,所以报错!
解决办法 :
先get你的目标网站 在添加cookie保持域一致:
1.webdriver.get(http://www.xxx.com);
2.webdriver.manage().addCookie(cookie)
3.webdriver.get(http://www.xxx.com); //重新请求目标网站
而且你没必要把cookie写入文件再读出来,直接用一个引用变量保持住你一开始拿到的cookie对象即可在后记测试中拿来用,只要session不失效 就OK。
我这有个实例:
  1. if (CookiesUtil.getCk() != null) {  
  2.             webDriver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);  
  3.             try {  
  4.                 webDriver.get(website);  
  5.             } catch (Exception e) {  
  6.             }  
  7.             webDriver.manage().addCookie(CookiesUtil.getCk());  
  8.         }  
  9.         try {  
  10.             webDriver.get(website);  
  11.         } catch (Exception e) {  
  12.         }  
  13.         webDriver.manage().timeouts().pageLoadTimeout(-1, TimeUnit.SECONDS);  
  14.     }  
复制代码

回复 支持 反对

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-11-26 13:19 , Processed in 0.066259 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表