Получение не может фокусировать элемент в хроме и краю с помощью java/selenium
Я получаю неспособность сфокусировать ошибку элемента при выполнении моего теста в chrome и edge в 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();
}
Вот трассировка стека:
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)
Вот еще одна трассировка стека. Я действительно получаю сообщение об ошибке при попытке щелкнуть кнопку отправки, а не активный флаг. Я уже выполнил действия, которые я также предоставил.
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)
код:
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();
Ответы
Ответ 1
Метод sendkeys является проблемой по трассировке стека.
at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:121)
Попробуйте Actions
класс, чтобы сначала сфокусироваться на элементе, а затем отправить необходимые ключи.
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.sendKeys("SOME DATA");
actions.build().perform();
Ответ 2
Разрешение действий действительно работало. У меня, видимо, была дополнительная строка driver.findElementBy, которая должна была быть прокомментирована, поскольку это был дубликат того, что я переместил в другое место.
Спасибо за помощь!
Ответ 3
В будущем, если другие сталкиваются с этой проблемой, убедитесь, что вы находите только один элемент! Инструменты Chrome иногда могут обманывать, когда дело доходит до этого.
Я снова проверил свой селектор в firePath (дополнение Firefox), и оказалось, что у меня было два совпадающих узла, хотя инструменты chrome показали мне один элемент.
https://addons.mozilla.org/en-US/firefox/addon/firepath/
Ответ 4
Я нашел очень важный код при чтении кода "Action class".
"Действие класс" Работает из-за
actions.click()
?!?
,
Попробуйте просто положить
element.click()
до
element.sendKeys()
в вашем существующем коде.
Метод click() фокусирует элемент !! ~~ спасибо для каждого старшего
Ответ 5
Выбранный ответ работал только частично для меня. Добавляя
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(element));
element.clear();
прежде чем использовать предложенный ответ, он работал полностью!
Ответ 6
Это отредактированная версия правильного ответа, так как я не смог просто скопировать и вставить этот код. С помощью кода ниже вы можете скопировать и вставить его (если элемент найден как 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()
Ответ 7
Может быть, установленный вами Xpath не соответствует этому уровню элемента. Например, если текстовое поле проходит через Div\div\textarea
то, скорее всего, вы берете только Div\
part. У меня была та же проблема, и она была решена после написания xpath до узла textarea
.