WebDriver通过XPath捕获文本

WebDriver通过XPath捕获文本,xpath,webdriver,selenium-webdriver,Xpath,Webdriver,Selenium Webdriver,我试图捕获一行文本,用于自动WebDriver测试,以便在稍后的比较中使用它。但是,我找不到一个可以与WebDriver一起使用的XPath。我以前使用过text()函数来捕获不在标记中的文本,但在本例中它不起作用。这是HTML,请注意,此文本将永远不会相同,因此我无法使用contains或类似函数 <div id="content" class="center ui-content" data-role="content" role="main"> <div data-isc

我试图捕获一行文本,用于自动WebDriver测试,以便在稍后的比较中使用它。但是,我找不到一个可以与WebDriver一起使用的XPath。我以前使用过text()函数来捕获不在标记中的文本,但在本例中它不起作用。这是HTML,请注意,此文本将永远不会相同,因此我无法使用contains或类似函数

<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>

WebDriver测试是用C#编写的。

python WebDriver代码类似

driver.find_element_by_xpath("//span[@class='ui-btn-text']").text
但是定位器可能不是uniqe,因为我看不到所有的代码


PS尽量不要使用诸如html/body/div[1]/div[2]/div/div/a[1]/span/span/code>

这样的定位器。您可以使用

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


我能够通过从XPath中删除span标记来解决这个问题

GetText("html/body/div[3]/div[2]/div/div/a[1]", SelectorType.XPath);
方法: 从给定的DOM中查找CSS选择器

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


使用C#Library方法获取文本。

难道不能简单地获取元素并调用吗?GetText使用下面Alexander答案中的选择器返回一个空字符串。使用问题中发布的定位器时,我遇到超时或无效路径异常。“GetText使用下面Alexander答案中的选择器返回空字符串”使用Firefox浏览器中的firebug+firepath检查定位器是否为Uniqe如何做到这一点?我知道如何检查firepath,但不知道如何判断此定位器是否唯一。请将xpath复制到firepath的xpath行,然后按“Enter”。它将告诉您使用您提供的XPath找到了多少个匹配项,共有37个匹配项,因此它不是唯一的。你能索引这些以获得第一个匹配项吗?我需要更多的html代码,至少
div/a[1]/span/span
这部分。或者,如果该页面是公开的,我可以给你确切的XPath。请告诉您正在使用的编程语言我也有同样的问题,我尝试了您的解决方案,但我发现一个错误“SelectorType无法解析为变量”。有什么我必须导入或声明的吗?SelectorType是我创建的用于保存WebDriver支持的元素选择器的枚举。我将其传递给我的WebDriver包装器方法,以便它们知道随它一起发送的字符串所使用的选择器(上面调用的是driver.FindElement(By.XPath(locator)))。
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();
}
GetText("html/body/div[3]/div[2]/div/div/a[1]", SelectorType.XPath);