我想点击左侧的 googlemaps 结果(边栏链接文本)。我只能用 xpath 或 cssSelector 方法点击第一个结果
ChromeOptions options=new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
WebDriver driver=new ChromeDriver(options);
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
JavascriptExecutor js = (JavascriptExecutor) driver;
NgWebDriver ngWebDriver = new NgWebDriver(js);
ngWebDriver.waitForAngularRequestsToFinish();
String urlGmaps = "https://www.google.com/maps/search/Air+Conditioning+Contractor+Air+Conditioning+Repair+Service+Contractor+OR+OR+OR+Repair+OR+Service+%22SAN+DIEGO%22/@32.7916817,-117.9672179,8z/data=!3m1!4b1";
driver.get(urlGmaps);
driver.manage().window().maximize();
WebDriverWait wait2= new WebDriverWait(driver, Duration.ofSeconds(30));
// variable x represents the odd numbers of the xpath
int x = 3;
String xp="//*[@id='QA0Szd']/div/div/div[1]/div[2]/div/div[1]/div/div/div[2]/div[1]/div["+ x + "]/div/a";
while (x < 7){
wait2.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xp)));
// the first result in the sidebar
driver.findElement(By.xpath(xp)).click();
//add plus 2 for the second and third results
x = x + 2;
Thread.sleep(5000);
// WebDriverWait wait2= new WebDriverWait(driver, Duration.ofSeconds(30));ebDriverWait wait2= new WebDriverWait(driver, Duration.ofSeconds(30));ebDriverWait wait2= new WebDriverWait(driver, Duration.ofSeconds(30));ebDriverWait wait2= new WebDriverWait(driver, Duration.ofSeconds(30));
// closes the window- click on the close window button
driver.findElement(By.xpath("//*[@id='QA0Szd']/div/div/div[1]/div[3]/div/div[1]/div/div/div[1]/div/div/div[3]/span/button")).click();
Thread.sleep(5000);
}
我用 cssSelector 方法尝试了相同的逻辑,但只对第一个结果有效
String selector= ("#QA0Szd > div > div > div.w6VYqd > div.bJzME.tTVLSc > div > div.e07Vkf.kA9KIf > div > div > div.m6QErb.DxyBCb.kA9KIf.dS8AEf.ecceSd > div.m6QErb.DxyBCb.kA9KIf.dS8AEf.ecceSd > div:nth-child(" + x + )");