Selenium Web驱动程序Ruby自动完成文本字段

Selenium Web驱动程序Ruby自动完成文本字段,ruby,selenium,autocomplete,textfield,Ruby,Selenium,Autocomplete,Textfield,我正在使用Ruby自动化Web浏览器 我在从“自动完成”字段的列表中选择一项时遇到了一个问题 例如: 当你输入一些文字时,在google.com上说“他”。我想从提供的建议中选择一项 我在堆栈上看到了按tag_name使用的建议 最新的SeleniumWebDriver中不推荐使用标记名 Java eqvivalent如下所示: public static void main(String[] args) throws InterruptedException { String textToS

我正在使用Ruby自动化Web浏览器

我在从“自动完成”字段的列表中选择一项时遇到了一个问题

例如: 当你输入一些文字时,在google.com上说“他”。我想从提供的建议中选择一项

我在堆栈上看到了按tag_name使用的建议 最新的SeleniumWebDriver中不推荐使用标记名

Java eqvivalent如下所示:

public static void main(String[] args) throws InterruptedException {

String textToSelect = "headlines today";

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
Thread.sleep(2000);
WebElement autoOptions= driver.findElement(By.id("lst-ib"));
autoOptions.sendKeys("he");

List<WebElement> optionsToSelect = driver.findElements(By.tagName("li"));

for(WebElement option : optionsToSelect){
    System.out.println(option);
    if(option.getText().equals(textToSelect)) {
        System.out.println("Trying to select: "+textToSelect);
        option.click();
        break;
    }
}
publicstaticvoidmain(String[]args)抛出InterruptedException{
String textToSelect=“今日头条”;
WebDriver=newfirefoxdriver();
驱动程序。获取(“https://www.google.co.in/");
《睡眠》(2000年);
WebElement autoOptions=driver.findElement(By.id(“lst-ib”);
自动选项。发送键(“he”);
列表选项toselect=driver.findElements(按.tagName(“li”);
for(WebElement选项:options to select){
System.out.println(选项);
if(option.getText().equals(textToSelect)){
System.out.println(“尝试选择:”+textToSelect);
选项。单击();
打破
}
}

我将编写与您所写内容相同的Ruby,但在此之前,我看不到当您通过send_键编写时列表会弹出,它只在您手动编写时才会弹出,而且在您获得一些有意义的单词之前,还有许多空列表正在打印

我写了下面的代码来了解索引

@driver.navigate.to("https://www.google.co.in/")
@driver.find_element(id: "lst-ib").send_keys 'he'
sleep 4
@driver.find_elements(tag_name: "li").each_with_index  do |value,index|
  puts value.text + index.to_s
end
我得到了这个输出,记住,因为列表没有弹出,我把sleep语句放在那里,所以只要在文本框中键入“he”,你就可以手动按下空格键

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
he man20
he like that lyrics21
he is22
he ram he ram23
he like that24
he durga maiya25
he is my everything lyrics26
he has or have27
he for she28
he ne laser29
30
Report inappropriate predictions31
因此1到19没有找到单词,因此我单击下面代码中的第20个单词

@driver.find_elements(tag_name: "li")[20].click

是否通过(标记名称)查找元素有效。我尝试过这个,似乎它在最新的selenium中被弃用了。@SabhapathiA不,它有效!我使用了最新的selenium,它有效。既然您决定使用Ruby selenium绑定,我建议您使用WATIR,它是Ruby selenium绑定的一个很好的框架包装器,计时不依赖于驱动程序,它由本地语言绑定维护d语法更简单。@Sabhapathi如果是的话,你能接受我的答案吗?我的答案左上方有一个勾号,你需要单击以接受我的答案。