import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DynamicXpaths {

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

    WebDriver driver= new FirefoxDriver();  


    List<WebElement> list=  driver.findElements(By.xpath("//div[@id='yui_3_12_0_1_1460454396950_758']/ul/li[starts-with(@id,'yui_3_12_0_1_1460')]/a")); 


  • 1
    Please provide HTML code (some of part only) – Sagar007 Apr 12 '16 at 11:12
  • Can you tell me which element list you want? - added on behalf of "siraj" – ECiurleo Apr 12 '16 at 12:42

You're trying to find a dynamically generated id using a static string. Everytime you go to the page 'yui_3_12_0_1_1460454396950_758' and 'yui_3_12_0_1_1460' will change. You have to find another way to find them.

| improve this answer | |

As Per my understanding you script is following steps :

  1. Open yahoo
  2. Search selenium
  3. Get list of links which are present in More link

So get list of elements(links)

List<WebElement> list=  driver.findElements(By.xpath("//div[@class='yui3-menu-content']/ul/li/a"));

Note : Further step that you perform is to click on first link so for that folow this step.


Let me know If any query.

| improve this answer | |
  • 1
    Can I know why this answer is down voted ? – Sagar007 Jun 8 '16 at 9:01
  • I think your xpath is not working so it may be down voted. – zishan paya Mar 10 '17 at 13:30
  • Which error you have found ? – Sagar007 Mar 10 '17 at 13:41
  • You are not point to auto complete seachText box and instead the top link and More (top menu) and the question is in search text box – zishan paya Mar 10 '17 at 13:47

As the list is shown in iframe so you need to switch to iframe first then try to find out the elements.

enter image description here

so your code should be

WebElement iframe = driver.findElement(By.xpath("//iframe[@class='sa-shim']"));

List<WebElement> list=  driver.findElements(By.xpath("//div[@id='yui_3_12_0_1_1460454396950_758']/ul/li[starts-with(@id,'yui_3_12_0_1_1460')]/a"));
| improve this answer | |
  • I believe, the search list not under iframe and the xpath you provide is invalid as id element is dynamic. – zishan paya Mar 10 '17 at 13:26

You can try to fetch the list using class parameter using CSS selector. Please try to use the below code instead of xpath.

By.cssSelector(".sa-panel.sa-gossip .sa-item")
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.