我想选择自动完成文本框中显示的第一个选项。下面是我尝试但未获得所需输出的代码。
public void clickSublink() throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
WebDriver dr=new ChromeDriver();
dr.get("http://demoqa.com/autocomplete/");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
dr.findElement(By.xpath("//ul[@id='ui-id-1']//child::li")).click();
}
答案 0 :(得分:1)
要从autocomplete文本框中选择第一个选项,您需要使用elementToBeClickable()
,并且可以使用以下任一Locator Strategies:
cssSelector
:
driver.get("http://demoqa.com/autocomplete/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.ui-autocomplete-input#tags"))).sendKeys("b");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ul.ui-autocomplete>li>div"))).click();
xpath
:
driver.get("http://demoqa.com/autocomplete/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='ui-autocomplete-input' and @id='tags']"))).sendKeys("b");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='ui-menu ui-widget ui-widget-content ui-autocomplete ui-front']/li/div"))).click();
答案 1 :(得分:0)
如果只想选择第一个选项,则可以使用硒中的键类。请在下面的代码中找到它。
public void clickSublink() throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
WebDriver dr=new ChromeDriver();
dr.get("http://demoqa.com/autocomplete/");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys(Keys.DOWN, Keys.ENTER);}
答案 2 :(得分:0)
另一种方法:
library (XML)
library(RCurl)
data=htmlParse("http://demoqa.com/autocomplete/")
result=xpathSApply(data,"normalize-space(substring-before(substring-after(//div[@class='demo-frame']//script[last()]/text(),'['),']'))")
reg=gsub('\"',"",result)
final=unlist(strsplit(reg,", "))
产生:
[1] "ActionScript" "AppleScript" "Asp" "BASIC" "C" "C++"
[7] "Clojure" "COBOL" "ColdFusion" "Erlang" "Fortran" "Groovy"
[13] "Haskell" "Java" "JavaScript" "Lisp" "Perl" "PHP"
[19] "Python" "Ruby" "Scala" "Scheme"