【发布时间】:2012-03-24 16:48:00
【问题描述】:
如果我在网格中列出的页面上有多个超链接,并且我只想将焦点放在第一个超链接上,有没有办法根据部分 href 文本获取对 a 标签的 href 的引用?
例如,假设页面有一堆带有汽车名称的超链接:
<a href="/Customers/7">Adam Backwell</a>
<a href="/Customers/12">Eric Mebratu</a>
<a href="/Customers/5">Dave Johnson</a>
<a href="/Customers/54">Tom Rogan</a>
所以我想为我的 xPath 做这样的事情:
"//table[@id='{0}']/a[href{1}]", usersGridId, "/Customers/");
因此,在其href 中获取第一个带有/Customers/ 的超链接。我不知道您是否可以只进行部分字符串匹配..或者换句话说,使用 XPath 进行正则表达式可以吗?在这种情况下,我不想依赖 CustomerId,因为我不知道该 Id 将是什么,因为网格是动态的。我只关心它获取对网格列表中第一个超链接的引用,不管它是谁。
更新:
忘了补充说我正在使用 XPath 和 Selenium Web 框架。
更新:
duh,我刚刚意识到我已经有那个表的参考(虽然你在这里看不到那个代码..抱歉)
所以我正在做类似 grid.FindElement(By.XPath(xPath));其中 grid 已经引用了一个表格元素。在这个表中是一个 tbody,所以我现在尝试使用这样的 a 元素:
IElement gridTable = GetCustomerGrid(); // now represents the table element that holds the customer list
xPath = string.Format("/tbody[@id='{0}']/a[1](contains(@href,'{1}')]", usersGridContainerId, "/Customers");
IWebElement hyperlink = gridTable.FindElement(By.XPath(xPath));
这个也没有运气。
还根据上面更新的代码尝试了以下方法:
string.Format("/tbody[@id='{0}']/a(contains(@href,'{1}')]",usersGridContainerId, "/Customers"); // did not find the hyperlink
string.Format("/tbody[@id='{0}']/a[1](starts-with(@href,'{1}')]",usersGridContainerId, "/Customers"); //invalid XPath Syntax error
string.Format("//tbody[@id='{0}']/a(contains(@href,'{1}')]",usersGridContainerId, "/Customers");
string.Format("//tbody[@id='{0}']/a(starts-with(@href,'{1}')]",usersGridContainerId, "/Customers");
这是我试图访问超链接的页面结构
<div class="table">
<table id="customerList">
<thead>
<tr>
<th class="column1">ID</th>
<th class="column2">Name</th>
<th class="column3">Email</th>
</tr>
</thead>
<tbody id="custListContainer">
<tr>
<td class="column1">7</td>
<td class="column2"><a href="/Customers/7">Joe Smith</a></td>
<td>someDude@gmail.com</td>
</tr>
.. next user, and so on
</tbody>
</table>
</div>
更新:
试过了,没有运气:
string xPath = (string.Format("//tbody[@id={0}]/tr/td/a(starts-with(@href, {1})", usersTableId, " /Customers/"));
OurSeleniumDriverInstance.FindElement(By.XPath(xPath ));
【问题讨论】:
-
此时要拔掉我的头发......真的很沮丧。