如何从谷歌搜索框的五个建议中随机选择一个建议

时间:2017-07-11 10:16:02

标签: selenium-webdriver

通过使用此代码,我可以点击所有建议中的一个建议。我无法随意点击建议。我需要随机点击一个建议并验证是否只显示了所显示的建议。

package google;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Google {
     public WebDriver driver;

     @Test(priority=1)
      public void Firefoxaccess() throws InterruptedException 
      {
          System.setProperty("webdriver.gecko.driver","C:/Users/naveenkumar.d/Downloads/geckodriver-v0.17.0-win64/geckodriver.exe");
          driver=new FirefoxDriver();
          driver.get("https://www.google.co.in/");
          driver.findElement(By.id("lst-ib")).sendKeys("n");
          Thread.sleep(3000);
          driver.findElement(By.xpath("/html/body/div/div[3]/form/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/ul/li[1]/div/div[2]")).click();
      }
  }

1 个答案:

答案 0 :(得分:0)

您可以根据rand方法撰写选择器。

例如: r =在此处生成随机数

,选择器应该是这样的:

//ul[@role='listbox']/li[r]

至于如何检查选项是否已被选中,您需要检查搜索input是否包含您的文字。

文字应what you typed与随机选项中的文字连接,即//ul[@role='listbox']/li[r]//b

中的文字

支票选择器://input[@name='q'][contains(@value, 'your_text')]