【问题标题】:Need to find element element with inner text需要找到带有内部文本的元素元素
【发布时间】:2018-03-10 22:23:09
【问题描述】:

我有一个包含多行记录的表。我有 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;          
}

【问题讨论】:

    标签: java selenium selenium-webdriver css-selectors


    【解决方案1】:

    你为什么不直接使用xpath

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

    这将为您提供带有 &lt;a&gt; 标签的上一个兄弟元素到具有 ID 的元素。

    【讨论】:

    • 感谢@Guy 的帮助,我通过更正“+i+”来使用我的 css 代码。但是我在其他一些地方使用了你的代码,我一直在寻找它。
    【解决方案2】:

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

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

    【讨论】:

    • 嗨@BoltClock,感谢您的回复。实际上,在发布问题后,我发现我错过了这些报价。现在工作正常。
    猜你喜欢
    • 2013-07-02
    • 2019-09-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多