使用xpath和Selenium检索表数据

时间:2015-05-27 10:40:29

标签: c# selenium

我的HTML看起来基本上像下面的

....
<div id="a">
<table class="a1">
<tbody>
<tr>
<td><a href="a11.html>a11</a>
</tr>
<tr>
<td><a href="a12.html>a12</a>
</tr>
</tbody>
<table>
</div>
...

我在C#中使用了以下编码,但是,我无法在此阶段检索URL

IWebElement baseTable =  driver.FindElement(By.ClassName(TableID));
// gets all table rows
ICollection<IWebElement> rows = baseTable.FindElements(By.TagName("tr"));
// for every row
IWebElement matchedRow = null;
foreach(var row in rows)
{
Console.Write (row.FindElements(By.XPath("td/a")));
}

2 个答案:

答案 0 :(得分:4)

首先,您给了我们无效的标记。对了一个:

&#13;
&#13;
<div id="a">
    <table class="a1">
        <tbody>
        <tr>
            <td>
                <a href="a11.html">a11</a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="a12.html">a12</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>
&#13;
&#13;
&#13;

如果表行中只有一个锚点,则应使用此代码检索url:

IWebElement baseTable = driver.FindElement(By.ClassName(TableID));
// gets all table rows
ICollection<IWebElement> rows = baseTable.FindElements(By.TagName("tr"));
// for every row
IWebElement matchedRow = null;
foreach (var row in rows)
{    
    Console.WriteLine(row.FindElement(By.XPath("td/a")).GetAttribute("href"));    
}

您需要获取找到的元素的href属性。否则,row.FindElement(By.XPath("td/a")将打印IWebElement继承类的类型名称,因为它是某种类型的对象,而不是字符串。

答案 1 :(得分:0)

这对我来说看起来不像是一个有效的xpath

Console.Write (row.FindElements(By.XPath("td/a")));

Console.Write (row.FindElements(By.XPath("/td/a")));