需要找到带有内部文本的元素元素

时间:2018-03-10 22:23:09

标签: java selenium selenium-webdriver css-selectors

我有一个包含记录行的表。我有ID“171485824993”作为我的数据来查看并需要获取文本值“New,Jersey”并单击文本作为其链接。 将有超过1个与此类似的记录,需要循环,直到找到具有我正在寻找的ID的正确行。

<div layout="row" class="table2Row ng-scope layout-row" ng-repeat="state in fullList">
  <div class="flex-inline top-bottom-margin-15 flex" flex="">
    <a ng-click="$ctrl.viewDetails(st)" flex="30" aria-label="St" tabindex="0" class="ng-binding flex-30">New, York</a>
    <p class="small ng-binding flex-10" flex="10">NY</p>
    <p class="small ng-binding flex-10" flex="10">M</p>
    <p class="small ng-binding flex-15" flex="15">01/28/1991</p>
    <p class="small ng-binding flex" flex="">171485421586</p>
    <p class="small ng-binding flex" flex="">M4398-1</p>
  </div>

<div layout="row" class="table2Row ng-scope layout-row" ng-repeat="state in fullList">
  <div class="flex-inline top-bottom-margin-15 flex" flex="">
    <a ng-click="$ctrl.viewDetails(st)" flex="30" aria-label="St" tabindex="0" class="ng-binding flex-30">New, Jersey</a>
    <p class="small ng-binding flex-10" flex="10">NJ</p>
    <p class="small ng-binding flex-10" flex="10">M</p>
    <p class="small ng-binding flex-15" flex="15">03/28/1996</p>
    <p class="small ng-binding flex" flex="">171485824993</p>
    <p class="small ng-binding flex" flex="">M4398-1</p>
  </div>

我尝试了以下代码但将错误视为无效选择器:指定了无效或非法选择器

List <WebElement> studentCount= driver.findElements(By.cssSelector(".table2Row"));
for (int i=0; i<studentCount.size();i++) {
    String studentName= driver.findElement(By.cssSelector(".table2Row:nth-of-type(i) p:nth-of-type(4)")).getText();
    if (studentName.equals("171485824993"))
        System.out.println (studentName);
        break;          
}

2 个答案:

答案 0 :(得分:1)

为什么不使用xpath

driver.findElement(By.xpath("//*[text()='171485824993']/preceding-sibling::a"));

这将为您提供带有<a>标记的上一个兄弟,并带有ID。

答案 1 :(得分:0)

您需要像对待任何其他字符串一样连接i

String studentName= driver.findElement(By.cssSelector(".table2Row:nth-of-type(" + i + ") p:nth-of-type(4)")).getText();