硒中的sendKeys函数无法获取焦点元素错误

时间:2019-01-15 20:19:13

标签: java selenium

尝试通过以下链接将任何数据发送到“来自文本字段”。 https://flights.msn.com/en-in/flight-search

代码如下:

WebDriverWait wait= new WebDriverWait(driver,20);

        WebElement dropdown=driver.findElement(By.xpath("(//a[@href='/en-in/weather'])[1]"));
        dropdown.click();
        driver.findElement(By.xpath("(//a[@href='/en-in/travel'])[1]")).click();
        driver.findElement(By.xpath("//li/a[@href='https://flights.msn.com/en-in/flight-search']")).click();
        //WebElement from=wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//div[@class='place-selector js-place-selector'])[1]")));
        WebElement from=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='search']/div[1]/div[3]/div")));
        //js.executeScript ("document.getElementById('from').focus();");
        //from.click();
        Thread.sleep(3000);
        //from.sendKeys(Keys.BACK_SPACE);
        from.sendKeys("Delhi");
        from.sendKeys(Keys.ENTER);

获取错误:

Error:org.openqa.selenium.WebDriverException: unknown error: cannot focus element

2 个答案:

答案 0 :(得分:1)

您需要将单词Delhi发送到a元素,然后等待列表出现,然后单击li包含它。

WebElement origin = driver.findElement(By.cssSelector("div.js-originplace a"));
Actions actions = new Actions(driver);
actions.moveToElement(origin).click().sendKeys("Delhi");
actions.build().perform();

WebElement from = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul//li[contains(., 'Delhi')]")));
from.click()

答案 1 :(得分:0)

我认为您尚未为from变量输入正确的xpath,忘记了在上一个div输入索引,如下所示,请查看它是否有帮助,请打印或粘贴所有控制台错误或信息

 WebElement from=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='search']/div[1]/div[3]/div")));

WebElement from=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='search']/div[1]/div[3]/div[index_no]")));

我认为可能是由于elementToBeClickable所致,您只需要更改并让我知道通过presentOfElement进行更改,就可以看看它是否起作用