Andrew
Andrew

Reputation: 811

WebDriver Capture Text by XPath

I am attempting to capture a line of text for an automated WebDriver test to use it in a comparison later on. However, I cannot find an XPath that will work with WebDriver. I have used the text() function before to capture text that is not in a tag, but in this instance that is not working. Here is the HTML, note that this text will never be the same, so I cannot use contains or similar functions.

<div id="content" class="center ui-content" data-role="content" role="main">
<div data-iscroll="scroller">
<div class="ui-corner-all ui-controlgroup ui-controlgroup-vertical" data-role="controlgroup">
<a class="ui-btn ui-corner-top ui-btn-hover-c" style="text-align: left" data-role="button" onclick="onDocumentClicked(21228772, "document.php?loan=********&folderseq=0&itemnum=21228772&pageCount=3&imageTypeName=1003 Application - Final&firstInitial=&lastName=")" href="#" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-theme="c">
<span class="ui-btn-inner ui-corner-top">
<span class="ui-btn-text">
<img class="checkMark checkMark21228772 notViewedCompletely" width="15" height="15" title="You have not yet viewed this document." src="../images/white_dot.gif"/>
1003 Application - Final. (Jan 11 2012  5:04PM)
</span>
</span>
</a>

In this example, the text I am attempting to capture is: 1003 Application - Final. (Jan 11 2012 5:04PM) I have inspected the element with Firebug and I have tried the following XPaths with no success.

html/body/div[1]/div[2]/div/div/a[1]/span/span
html/body/div[1]/div[2]/div/div/a[1]/span/span/text()

The WebDriver test is being written in C#.

Upvotes: 1

Views: 5726

Answers (4)

user3487861
user3487861

Reputation: 350

Approach: Find the CSS Selector from the Given DOM

Derived CSS:css=#content div.ui-controlgroup > a[onclick*='onDocumentClicked'] > span > span

Use the C# Library Method to get the Text.

Upvotes: 0

Andrew
Andrew

Reputation: 811

I was able to solve this issue by removing the span tags from the XPath.

GetText("html/body/div[3]/div[2]/div/div/a[1]", SelectorType.XPath);

Upvotes: 1

Puran Joshi
Puran Joshi

Reputation: 3726

You can either use this

driver.FindElement(By.XPath(".//div[@id='content']/following-sibling::span[@class='ui-btn-text']") 

or

var elem = driver.FindElement(By.Id("Content"));
string text = string.Empty;
if(elem!=null) {
   var textElem = elem.FindElement(By.Xpath(".//following-sibling::span[@class='ui-btn-text']"));
   if(textElem!=null) text = textElem.Text();
}

Upvotes: 1

Furious Duck
Furious Duck

Reputation: 2019

python webdriver code looks something like

driver.find_element_by_xpath("//span[@class='ui-btn-text']").text

But locator may be not uniqe, because I can't see all the code

PS Try to never use locators like html/body/div[1]/div[2]/div/div/a[1]/span/span

Upvotes: 0

Related Questions