Find an element by text and get xpath
I have a table with 9 rows and 6 columns in my webpage. I want to search for a text "MakeGoodDisabled-Programwise_09_44_38_461(n)" and get the xpath of the cell. I have used the following but it fails because it is not able to find the text in the page. Can you please help? I am using Selenium Webdriver Junit to code this.
`List<WebElement> links = driver.findElements(By.tagName("td"));
Iterator<WebElement> itr = links.iterator();
while(itr.hasNext()){
String test = itr.next().getText();
if(test.equals("MakeGoodDisabled-Programwise_09_44_38_461(n)")){
String xpath = driver.findElement(By.name(test)).getAttribute("xpath");
System.out.println(xpath);
}
}`
My intention is to find a text in a table and get the corresponding next column value in the same row. I thought that I will replace the column number found by fetching the xpath with the column number I want. is there a better way to do it
Of course there's a way. Here's one possible solution.
Get all the rows:
While (iterate over row)
While(Iterate over column)
if(column.Text=='YOUR_MATCH'){
int voila=column.Index
}
}
}
Now you can simply move to that particular index for the other rows; or you could use xpath like .../tr/td[voila]
to retrieve all cells for that particular column.
I've written an approach, please don't take to be real-working-code!
You can also use this to crawl up and generate the xpath:
Call the method below with
generateXPATH(element, "");
The output will be something like:
/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[2]/div[1]/input[2]
METHOD
private String generateXPATH(WebElement childElement, String current) {
String childTag = childElement.getTagName();
if(childTag.equals("html")) {
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) {
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag)) {
count++;
}
if(childElement.equals(childrenElement)) {
return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
}
}
return null;
}
The XPath of an element is not a definitive value. An element can be found by many XPaths.
You cannot use Webdriver to extract an XPath and even if you could, it is unlikely to be the most efficient or sensible one, that can only be defined by the automator.
链接地址: http://www.djcxy.com/p/88590.html上一篇: seekBar更新Android的MediaPlayer视频时不顺畅
下一篇: 通过文本查找元素并获取xpath