使用Selenium网络驱动程序,我正在尝试在Google搜索框中搜索“ Selenium”,它提供了几种文本的自动建议。然后,我尝试从自动建议列表中单击一种特定的文本。看来,我的Xpath无法正常工作。
下面是我写的代码:
package com.initial.selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GoogleSearch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Shahid\\eclipse-
workspace\\InitialSeleniumProject\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath("//*[@name='q']")).sendKeys("selenium");
List < WebElement >
mylist=driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']/span"));
System.out.println(mylist.size());
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i).getText());
if (mylist.get(i).getText().contains("Selenium Benefits")) {
mylist.get(i).click();
break;
}
}
}
答案 0 :(得分:1)
试试这个:
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//ul[@role='listbox']//li/descendant::span"), 0));
System.out.println("no. of suggestions:"+options.size());
for(int i=0;i<options.size();i++) {
System.out.println(options.get(i).getText());
}
答案 1 :(得分:0)