获取无法使用 java/selenium 在 chrome 和 edge 中聚焦元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34537344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:45:20  来源:igfitidea点击:

getting cannot focus element in chrome and edge using java/selenium

javagoogle-chromeseleniumselenium-webdrivermicrosoft-edge

提问by Janet

I am getting a cannot focus element error when running my test in chrome and edge in FF it works fine. I have tried posted resolutions but to no avail. I am not sure what to do about this. Hoping someone out there can help. Thanks in advance.

在 chrome 和 FF 中运行我的测试时,我遇到了无法聚焦元素错误,它工作正常。我试过发布的决议,但无济于事。我不知道该怎么办。希望有高人能帮帮忙。提前致谢。

driver.findElement(By.linkText("Add")).click();
List <WebElement> groups = new Select(driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/fieldset/div[3]/div[2]/div/div/div[1]/select"))).getOptions();
groups.get(3).click();
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement groupRole = driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/fieldset/div[3]/div[2]/div/div/div[2]/label[2]"));
js.executeScript("arguments[0].click();", groupRole);
driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/fieldset/div[3]/div[2]/div/div/div[2]/label[2]")).sendKeys(" ");
// Check to see if the user should be made active and set active checkbox to on if value in file is "active"
if (activeFlag.equals("active"))
{
    driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/fieldset/div[3]/div[1]/div[1]/div/div/input")).sendKeys(" ");
} 
// If the user role is to be admin then set the Site role to Administrator
if (userLevel.equals("admin"))
{
    List <WebElement> roles = new Select(driver.findElement(By.name("community_role"))).getOptions();
    roles.get(1).click();
}

Here is the stack trace:

这是堆栈跟踪:

 Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot focus element
      (Session info: chrome=47.0.2526.106)
      (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 10.0 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 81 milliseconds
    Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
    System info: host: 'Janet-PC', ip: '192.168.56.1', os.name: 'Windows 8.1', os.arch: 'x86', os.version: '6.3', java.version: '1.7.0_80-ea'
    Session ID: 0a9dbd54a81a42a4178b25b95bb14f63
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{platform=WIN8_1, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\Janet\AppData\Local\Temp\scoped_dir7508_15608}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=47.0.2526.106, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, hasTouchScreen=false, applicationCacheEnabled=false, takesScreenshot=true}]
        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.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
        at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
        at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:121)
        at Viddler_create_user.createUser.test(createUser.java:244)
        at Viddler_create_user.createUser.setUpBeforeClass(createUser.java:126)
        at Viddler_create_user.createUser.main(createUser.java:64)

Here is another stack trace. I am actually getting the error when trying to click the submit button not the active flag. I had already done the actions steps which I will also provide.

这是另一个堆栈跟踪。尝试单击提交按钮而不是活动标志时,我实际上遇到了错误。我已经完成了我也将提供的操作步骤。

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot focus element
  (Session info: chrome=47.0.2526.106)
  (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 10.0 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 52 milliseconds
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
System info: host: 'Janet-PC', ip: '192.168.56.1', os.name: 'Windows 8.1', os.arch: 'x86', os.version: '6.3', java.version: '1.7.0_80-ea'
Session ID: f332b496aa54d581c764f7328e770e65
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=WIN8_1, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\Janet\AppData\Local\Temp\scoped_dir2072_18936}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=47.0.2526.106, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, hasTouchScreen=false, applicationCacheEnabled=false, takesScreenshot=true}]
    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.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:121)
    at Viddler_create_user.createUser.test(createUser.java:244)
    at Viddler_create_user.createUser.setUpBeforeClass(createUser.java:126)
    at Viddler_create_user.createUser.main(createUser.java:64)

Code:

代码:

        Actions actions = new Actions(driver);
        actions.moveToElement(driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/input[2]")));
        actions.click();
//      actions.sendKeys(" ");
        actions.build().perform();

采纳答案by parishodak

sendkeys method is the problem as per the stack trace.

根据堆栈跟踪,sendkeys 方法是问题所在。

at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:121)

Please try Actionsclass to first focus on the element then send required keys.

请尝试Actionsclass 首先关注元素,然后发送所需的键。

Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys("SOME DATA");
actions.build().perform();

回答by Janet

The Actions resolution did work after all. I apparently had an extra driver.findElementBy line that should have been commented out as it was a duplicate to something I had moved to another location.

毕竟,行动决议确实奏效了。我显然有一个额外的 driver.findElementBy 行,它应该被注释掉,因为它与我移动到另一个位置的东西重复。

Thanks for your help!!

谢谢你的帮助!!

回答by Valeriya

For future reference, if others run into this issue, make sure you're only finding one element! Chrome tools can be deceiving sometimes when it comes to this. I re-checked my selector in firePath (firefox add-on) and it turned out that I had two matching nodes, even though chrome tools showed me one element.

为了将来参考,如果其他人遇到此问题,请确保您只找到一个元素!在这方面,Chrome 工具有时会具有欺骗性。我在 firePath(firefox 附加组件)中重新检查了我的选择器,结果发现我有两个匹配的节点,尽管 chrome 工具向我显示了一个元素。

https://addons.mozilla.org/en-US/firefox/addon/firepath/

https://addons.mozilla.org/en-US/firefox/addon/firepath/

回答by ???

I Found very important code while reading "Action class" code.

我在阅读“动作类”代码时发现了非常重要的代码。

"Action class" Works because of

“动作类”的作品因为

actions.click()  

?!?

?!?

.

.

Try Just putting

试一试

element.click()

before

element.sendKeys()

in your existing code.

在您现有的代码中。

click() method makes element focused!!~~ THX for every senior

click() 方法使元素成为焦点!!~~感谢每一位前辈

回答by Alex

The chosen answer worked only partially for me. By adding

选择的答案只对我有用。通过添加

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
element.clear();

before using the suggested answer, it worked completely!

在使用建议的答案之前,它完全有效!

回答by Romano

This is an edited version of the correct answer, as I was unable to just copy paste that code. With the code below you can copy paste it (If the element is found as id):

这是正确答案的编辑版本,因为我无法复制粘贴该代码。使用下面的代码,您可以复制粘贴它(如果发现元素为 id):

elem = driver.find_element_by_id("WHATEVER THE ELEMENT ID IS HERE")
actions = ActionChains(driver)
actions.move_to_element(elem)
actions.click()
actions.send_keys("PUT YOUR TEXT IN HERE")
actions.perform()

回答by Hemant Madan

May be the Xpathyou have set is not up to that element level. E.g. if a text box is traversing through Div\div\textareathen most probably, you are taking only Div\part. I had the same problem and it got resolved after writing xpath upto textareanode.

可能是您设置的Xpath达不到该元素级别。例如,如果一个文本框正在遍历,Div\div\textarea那么很可能你只是Div\参与其中。我遇到了同样的问题,在将 xpath 写入textarea节点后它得到了解决。