使用Selenium WebDriver和Java跨类getText()

时间:2017-11-17 11:32:33

标签: java xpath selenium-webdriver

其中一行中的一行包含下面的td可用,我想在单独的字符串中获取span类值(其动态n个数量的span可用), 表示1111 FRANKLIN STREET OAKLAND, CALIFORNIA 94607-5200

HTML

<td colspan="5">
    <p class="caption">Assignee</p>
    <a class="ng-binding ng-scope" alt="View assignment(s)" ui-sref="search.resultAssignee(goToAssignee(assignee))" ng-repeat-start="assignee in abstract.patAssigneeName track by $index" href="#assigneeName=THE%20REGENTS%20OF%20THE%20UNIVERSITY%20OF%20CALIFORNIA">UNIVERSITY OF CALIFORNIA</a>
    <p class="ng-scope">
        <span class="ng-binding ng-scope" ng-if="abstract.patAssigneeAddress1[$index] !== ''">1111 FRANKLIN STREET<br></span>
        <span class="ng-binding ng-scope" ng-if="abstract.patAssigneeCity[$index] !== '' && abstract.patAssigneeState[$index] !== ''">OAKLAND, CALIFORNIA 94607-5200<br></span>
        <span class="ng-binding"> </span>
    </p>
    <br class="ng-scope" ng-repeat-end="">
</td>

我使用下面的XPath轻松获得受让人名称(使用表格迭代):

String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", "");

请帮助获取span类值。

2 个答案:

答案 0 :(得分:2)

首先获取所有span元素并将它们保存在WebElement列表中。然后在循环中使用getText()获取元素。你可以使用如下:

List<WebElement> allSpanElements = driver.findElements(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/p[2]/span"));
for (WebElement elem : allSpanElements) {
    String address = elem.getText();
    //System.out.println(address);
}

您可以使用它来保留String数组中的值。

您也可以尝试使用类名而不是像< - / p>这样的xpath

By.className("ng-binding ng-scope");

答案 1 :(得分:0)

正如您所提到的,您可以使用以下xpath轻松获取受理人姓名:

create table #MyTable(ProductId int, [Name] varchar(16))
insert into #MyTable
values
(101,'John'),
(201,'Marry'),
(301,'Marry'),
(401,'John'),
(501,'John')

select distinct
    t.[Name]
    ,ProductId = STUFF((
                      SELECT ',' + cast(t2.ProductId as char(3))
                      FROM #MyTable t2
                      WHERE t.[Name] = t2.[Name]
                      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
    #MyTable t


drop table #MyTable

现在,要在单独的字符串中获取span类值,例如 String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", ""); ,您可以使用以下代码块:

1111 FRANKLIN STREET OAKLAND , CALIFORNIA 94607-5200