gpt4 book ai didi

java - Selenium 发送键(文本),从下拉列表中选择并按 Enter 键

转载 作者:行者123 更新时间:2023-12-02 02:57:26 28 4
gpt4 key购买 nike

我正在尝试搜索此网站:http://www.jackson-stops.co.uk/

数据未显示在 URL 中,因此我使用的是 chromedriver。

我的代码是:

   public static void main(String[] args) {
//setup chromedriver
File file = new File("C:\\Users\\USER\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.jackson-stops.co.uk/");
//begin the simulation
WebElement menu = driver.findElement(By.xpath("//*[@id=\"sliderLocation\"]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
menu.sendKeys("Knightsbridge");
Thread.sleep(4000);
Select menu2 = new Select(menu);
menu2.selectByVisibleText("Knightsbridge");
Thread.sleep(4000);
} catch (Exception exp) {
System.out.println("exception:" + exp);
//close and quit windows
driver.close();
driver.quit();
}
//close and quit windows
driver.close();
driver.quit();
}

我得到的错误是:

   exception:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"

我如何能够选择一个位置并按回车键,因为我尝试检查 HTML 并且选项是动态加载的,因此不可见!

最佳答案

您正在尝试选择一个元素,但它不是选择列表,而是一个链接,因此您所要做的就是单击该元素,仅此而已

首先传递值

driver.findElement(By.xpath("//*[@id='sliderLocation']")).sendKeys("Knightsbridge")

完成后,它会填充值,因此您需要单击其中一个选项,因此您可以像这样直接单击该元素(因为此填充需要时间,您需要使用隐式等待

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS))

然后写

driver.findElement(By.xpath("//a[text()='Knightsbridge, London']")).click()

或者,如果您想选择由 Knightsbridge 组成的元素,则编写以下代码,这将选择由 Knightsbridge 组成的第一个选项,然后编写

driver.findElement(By.xpath("//a[contains(text(),'Knightsbridge']")).click()

您不必在 selenium 代码中的任何位置使用 sleep 语句,selenium 在单击后会自动等待,直到一切正常稳定下来。一种特殊情况是,如果您的页面在将值放入文本框中后刷新(对于 select_list 不需要),那么您需要使用隐式等待,否则甚至不需要隐式等待。

上面的代码是我从Ruby转换成Java的,我用来检查的原始代码是来自selenium Ruby绑定(bind),代码如下

@driver.find_element(:xpath, "//*[@id='sliderLocation']").send_keys "Knightsbridge"
@driver.manage.timeouts.implicit_wait = 10
@driver.find_element(:xpath, "//a[contains(text(),'Knightsbridge')]").click
@driver.find_element(:xpath, "//a[text()='Knightsbridge, London']").click

关于java - Selenium 发送键(文本),从下拉列表中选择并按 Enter 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870881/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com