Java 如何通过Selenium Webdriver将文本发送到搜索字段?
任务: 在搜索框中搜索FAA: 我试过这个:-Java 如何通过Selenium Webdriver将文本发送到搜索字段?,java,selenium,selenium-webdriver,xpath,css-selectors,Java,Selenium,Selenium Webdriver,Xpath,Css Selectors,任务: 在搜索框中搜索FAA: 我试过这个:- 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).
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
根据定义,Selenium与浏览器的交互就像真实用户一样。真正的用户将无法在隐藏的文本框/编辑框中键入内容。您需要更改输入的可见性,重新评估为什么需要与隐藏元素交互,或者使用javascript executor设置输入的值,如下所示:
driver.executeScript("arguments[0].value='" + textToEnter + "'", element);
使用以下xpath:
(//input[@id='search-text'])[2]
并使用类似于:
driver.findElement(By.xpath("(//input[@id='search-text'])[2]")).sendKeys("FAA");
当您在控制台中通过此id查找时,它提供了两个元素,第一个元素不可见,但第二个元素是实际的输入框。向网站上的搜索字段发送字符序列
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");
- 浏览器快照:
请提供HTML源代码。