简体   繁体   中英

How to select items from drop down menu using Selenium?

I have been trying to automate a search using Selenium. I simply want to search terms (say Pink Floyd ) but the file type should be pdf. Here is what I have done so far:

    //Query term
    WebElement element = driver.findElement(By.name("as_q"));
    String finalQuery = "pink floyd";
    element.sendKeys(finalQuery);

    //File type selection
    WebElement elem = driver.findElement(By.id("as_filetype_button"));
    elem.sendKeys("Adobe Acrobat pdf (.pdf)");
    driver.findElement(By.xpath("/html/body/div[1]/div[4]/form/div[5]/div[9]/div[2]/input[@type='submit']")).click();

This puts the term in the appropriate place and the drop down for file types are expanded but pdf option is not selected. Any help?

I am using Selenium 2.53.0.

EDIT

The following code segment perfectly worked as per the accepted answer for this question. However, all on a sudden the code segment is not working. I am a bit surprised to find this out. Previously, I was able to select PDF automatically with the following code segment but now, nothing gets selected.

 WebElement element = driver.findElement(By.name("as_q"));
 String finalQuery = "pink floyd";
 element.sendKeys(finalQuery);
 driver.findElement(By.id("as_filetype_button")).click();
 driver.findElement(By.xpath("//li[@class=class-name][@value='pdf']")).click();

This is how i do it, find the li that matches the class='goog-menuitem' and value='pdf' , i inspected the element. You can go directly with value='pdf' but just to make sure we are looking at the file type dropdown we added the class.

        driver.findElement(By.id("as_filetype_button")).click();
        driver.findElement(By.xpath("//li[@class='goog-menuitem'][@value='pdf']")).click();

You can still declare it with WebElement , i just prefer it shorthand. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM