Selenium的Java代码在正常运行测试时成功,但在以无头模式运行时失败。

huangapple go评论113阅读模式
英文:

Selenium java code runs test successfully but fails when run as headless

问题

以下是翻译好的部分:

我的Java Selenium测试用例在Chrome版本77上以`options.setHeadless(false);`运行正常但当我将这一行更改为`options.setHeadless(true);`时失败

这段Java代码是由Katalon Selenium Recorder Chrome扩展导出的

`options.setHeadless(false);`运行正常时的输出

页面标题是9 -> 扫描历史
页面标题是10 -> 扫描历史
页面标题是10.1 -> 扫描历史
页面标题是10.2 -> 扫描历史
页面标题是10.3 -> 扫描历史
页面标题是10.4 -> 扫描历史
页面标题是10.5 -> 扫描历史

当我使用`options.setHeadless(true);`运行相同的代码时我会收到以下警告以及错误消息并且执行在完成之前终止

页面标题是10 -> 扫描历史
[0530/125542.102:INFO:CONSOLE(0)] "解析头部X-XSS-Protection时出错:1;mod
e=block, 1;mode=block:预期在字符位置13处有分号。将应用默认
保护。"来源https://qualysguard.myshop.com/fo/scan/sca
nList.php0
页面标题是10.1 -> 扫描历史
页面标题是10.2 -> 扫描历史
页面标题是10.3 -> 扫描历史
主线程异常 "main" org.openqa.selenium.NoSuchElementException: 没有这样的元素无法定位元素{"method""css选择器""selector""#ext-gen
117"}
会话信息headless chrome=77.0.3865.75
有关此错误的文档请访问https://www.seleniumhq.org/except
ions/no_such_element.html
构建信息版本:'3.141.59',修订版:'e82be7d358',时间:'2018-11-14T08:17
:03'
系统信息主机:'myhostserver',IP"10.9.111.32"操作系统名称"Windows Serve
r 2012 R2"操作系统架构"amd64"操作系统版本"6.3"Java版本"1.8.0_45"
驱动程序信息org.openqa.selenium.chrome.ChromeDriver
功能 {acceptInsecureCertsfalsebrowserNamechromebrowserVersion7
7.0.3865.75chrome{chromedriverVersion77.0.3865.40f484704e052e0...userD
ataDirC:\Users\1886\AppData\Loc...}googchromeOptions{debuggerAddressl
ocalhost56128}javascriptEnabledtruenetworkConnectionEnabledfalsepageL
oadStrategynormalplatformXPplatformNameXPproxyProxy()setWindowRe
cttruestrictFileInteractabilityfalsetimeouts{implicit0pageLoad30
0000script30000}unhandledPromptBehaviordismiss and notify}
会话ID"09a309a747f7bcb42735bb8b6c39ad1f"
*** 元素信息{使用= id= ext-gen117}
在sun.reflect.NativeConstructorAccessorImpl.newInstance0本机方法创建以下内容本机方法

在sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
在sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)在java.lang.reflect.Constructor.newInstance(Unknown Source)在org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(
W3CHttpResponseCodec.java:187)在org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:122)在org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:49)在org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExe
cutor.java:158)在org.openqa.selenium.remote.service.DriverCommandExecutor.execute(Driv
erCommandExecutor.java:83)在org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.ja
va:552)在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:323)在org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebD
river.java:372)在org.openqa.selenium.By$ById.findElement(By.java:188)在org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:315)在pack.QualysScan.testQualysScan(QualysScan.java:182)中查找pack.QualysScan.main(QualysScan.java:284)

以下是涉及问题的代码部分

System.out.println("页面标题是10 -> " + driver.getTitle());
driver.findElement(By.id("body-header")).click();
driver.get("https://qualysguard.myshop.com/fo/scan/scanList.php");
System.out.println("页面标题是10.1 -> " + driver.getTitle());
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Add to my Calendar'])[1]/following::em[2]")).click();
System.out.println("页面标题是10.2 -> " + driver.getTitle());
System.out.println("页面标题是10.3 -> " + driver.getTitle());
driver.findElement(By.id("ext-gen117")).click();
System.out.println("页面标题是10.4 -> " + driver.getTitle());
System.out.println("页面标题是10.5 -> " + driver.getTitle());
String your_title = "启动合规扫描";

以下是驱动程序的设置部分

public static void setUp() throws Exception {
          System.setProperty("webdriver.chrome.driver", "H:\\Downloads\\Qualys\\vdi\\chromedriver.exe");
          ChromeOptions options =  new ChromeOptions();
          options.setHeadless(true);
          DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
    capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
    options.merge(capabilities);
    driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  }

如果您有任何其他疑问,请随时问我。

英文:

My java selenium java test case with Chrome version 77 runs fine when options.setHeadless(false); but fails when I change this line options.setHeadless(true);

The java code was exported by the katalon selenium recorder chrome extension.

Output when it runs fine with options.setHeadless(false);:

Title of the page is 9 -> Scan History
Title of the page is 10 -> Scan History
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Title of the page is 10.4 -> Scan History
Title of the page is 10.5 -> Scan History

When I run the same code with options.setHeadless(true); I get a below warning as well as an error message and the execution terminates before completion.

Title of the page is 10 -> Scan History
[0530/125542.102:INFO:CONSOLE(0)] "Error parsing header X-XSS-Protection: 1; mod
e=block, 1;mode=block: expected semicolon at character position 13. The default
protections will be applied.", source: https://qualysguard.myshop.com/fo/scan/sca
nList.php (0)
Title of the page is 10.1 -> Scan History
Title of the page is 10.2 -> Scan History
Title of the page is 10.3 -> Scan History
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such e
lement: Unable to locate element: {"method":"css selector","selector":"#ext\-gen
117"}
(Session info: headless chrome=77.0.3865.75)
For documentation on this error, please visit: https://www.seleniumhq.org/except
ions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17
:03'
System info: host: 'myhostserver', ip: '10.9.111.32', os.name: 'Windows Serve
r 2012 R2', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 7
7.0.3865.75, chrome: {chromedriverVersion: 77.0.3865.40 (f484704e052e0..., userD
ataDir: C:\Users\1886\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: l
ocalhost:56128}, javascriptEnabled: true, networkConnectionEnabled: false, pageL
oadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRe
ct: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 30
0000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 09a309a747f7bcb42735bb8b6c39ad1f
*** Element info: {Using=id, value=ext-gen117}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)
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(W3CHttpRe
sponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpRe
sponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExe
cutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(Driv
erCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.ja
va:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebD
river.java:372)
at org.openqa.selenium.By$ById.findElement(By.java:188)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDrive
r.java:315)
at pack.QualysScan.testQualysScan(QualysScan.java:182)
at pack.QualysScan.main(QualysScan.java:284)

Here is the part of the code concerning the issue:

System.out.println("Title of the page is 10 -> " + driver.getTitle());
driver.findElement(By.id("body-header")).click();
driver.get("https://qualysguard.myshop.com/fo/scan/scanList.php");
System.out.println("Title of the page is 10.1 -> " + driver.getTitle());
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Add to my Calendar'])[1]/following::em[2]")).click();
System.out.println("Title of the page is 10.2 -> " + driver.getTitle());
System.out.println("Title of the page is 10.3 -> " + driver.getTitle());
driver.findElement(By.id("ext-gen117")).click();
System.out.println("Title of the page is 10.4 -> " + driver.getTitle());
System.out.println("Title of the page is 10.5 -> " + driver.getTitle());
String your_title = "Launch Compliance Scan";

And here is how the driver is setup:

public static void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "H:\\Downloads\\Qualys\\vdi\\chromedriver.exe");
ChromeOptions options =  new ChromeOptions();
options.setHeadless(true);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
options.merge(capabilities);
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}

I'm sharing snapshot of element ext\-gen117 as visible on the portal.

Selenium的Java代码在正常运行测试时成功,但在以无头模式运行时失败。

Selenium的Java代码在正常运行测试时成功,但在以无头模式运行时失败。

Video of the issue:

https://www.youtube.com/watch?v=abSwsPtOOG4

Can you please suggest how can I overcome the issue?

答案1

得分: 1

这很可能是浏览器和Selenium之间的竞态条件导致的,Selenium尝试在DOM中不存在某个元素之前点击它。使用显式等待应该可以解决这个问题:

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("ext-gen117")));
element.click();
英文:

This is likely caused by a race condition between the browser and selenium, where selenium attempts to click on something before it exists in the DOM. Using an explicit wait should resolve the issue:

WebDriverWait wait = new WebDriverWait (driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("ext-gen117");
element.click();

huangapple
  • 本文由 发表于 2020年5月30日 16:37:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/62099924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定