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();
driver.navigate().to("http://yahoo.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='UHSearchBox']")).sendKeys("selenium");
Thread.sleep(10000);
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"));
System.out.println(list.size());
list.get(0).click();
}
}
-
1Please provide HTML code (some of part only)– Sagar007Apr 12, 2016 at 11:12
-
Can you tell me which element list you want? - added on behalf of "siraj"– ECiurleoApr 12, 2016 at 12:42
4 Answers
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.
As Per my understanding you script is following steps :
- Open yahoo
- Search selenium
- 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.
driver.findElements(By.id("yucs-more-link")).click();
Thread.sleep(1000);
list.get(0).click();
Let me know If any query.
-
1
-
-
-
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 Mar 10, 2017 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.
so your code should be
WebElement iframe = driver.findElement(By.xpath("//iframe[@class='sa-shim']"));
driver.switchTo().frame(iframe);
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"));
-
I believe, the search list not under iframe and the xpath you provide is invalid as id element is dynamic. Mar 10, 2017 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")