如何通过Selenium Webdriver将文本发送到搜索字段?

时间:2018-07-18 09:37:11

标签: java selenium selenium-webdriver xpath css-selectors

任务: 在搜索框中搜索FAA: enter image description here

我已经尝试过:-

webdriver.select_tabs(search.btnSearch);

Thread.sleep(3000);
WebElement searchbox = driver.findElement(By.id("search-text"));
Actions builder = new Actions(driver);
Actions seriesOfActions = builder.moveToElement(searchbox).click().sendKeys(searchbox, "FAA");
seriesOfActions.perform();

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"search-text\"]")));
element.sendKeys("FAA");
element.sendKeys(Keys.ENTER);

webdriver.enter_key(search.txtSearch, Keys.ENTER);
webdriver.enter_Text(search.txtSearch, "FAA");
webdriver.enter_key(search.txtSearch, Keys.ENTER);

收到此错误:-

org.openqa.selenium.ElementNotVisibleException: element not visible

3 个答案:

答案 0 :(得分:1)

在xpath下使用:

(//input[@id='search-text'])[2]

并使用类似:

driver.findElement(By.xpath("(//input[@id='search-text'])[2]")).sendKeys("FAA");

在控制台中通过此ID查找时,它提供了两个元素,第一个元素不可见,但第二个元素是实际的输入框。

答案 1 :(得分:0)

根据定义,Selenium会像真实用户一样与浏览器进行交互。真正的用户将无法在隐藏的文本框/编辑框中键入内容。您需要更改输入的可见性,重新评估为什么需要与隐藏元素进行交互,或者使用javascript executor来设置输入的值,如下所示:

driver.executeScript("arguments[0].value='" + textToEnter + "'", element);

答案 2 :(得分:0)

要将字符序列发送到网站https://faatoday.com/上的搜索字段,您需要诱使 WebDriverwait 等待搜索图标可点击,然后再次诱导 WebDriverWait ,以使所需的元素可点击,然后按如下所示发送字符序列:

  • 代码块:

    driver.get("https://faatoday.com/");
    new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#navbarNav span.sicon-holder.fabutton#searchicon>i.fa.ssearch.fa-search.fa-lg#sicons"))).click();
    new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='navbarNav']//input[@class='search-text form-control mr-sm-2' and @id='search-text']"))).sendKeys("FAA");
    
  • 浏览器快照:

faatoday_search