gpt4 book ai didi

java - Selenium Google Places 自动完成 Java

转载 作者:行者123 更新时间:2023-11-30 07:14:55 25 4
gpt4 key购买 nike

我正在尝试自动化 Google 自动建议并使用 Selenium 选择随机建议。

WebElement element = driver.findElement(By.xpath("//input[@id='id_address']"));
element.sendKeys(“whi”);

如何从 Google 建议列表中选择随机建议?

最佳答案

首先,您需要找到代表自动完成建议选项的所有匹配元素。由于自动完成建议的出现是异步的,因此您需要使用循环或 WebDriverWait 等待它们出现。 。获取 List<WebElement> 的行list 将继续尝试查找与给定选择器匹配的元素,并且仅当列表(来自它包装的 driver.findElements 调用)不为空时才返回。如果它在给定的超时时间内(在本例中是 10 构造函数中的 WebDriverWait 秒)找不到非空列表,它将抛出 TimeoutException 。 。然后,一旦您获得了建议列表,只需从该列表中随机选择一个并单击它即可。

driver.get("https://www.google.com");
driver.findElement(By.name("q"))
.sendKeys("whi");
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("[role='option']"), 0));
int index = (int) (Math.random() * options.size());
options.get(index)
.click();

关于java - Selenium Google Places 自动完成 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573436/

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