【问题标题】:Getting the text of a webelement through xpath通过 xpath 获取 webelement 的文本
【发布时间】:2014-08-29 15:49:11
【问题描述】:

我正在尝试通过 xpath 获取 webelement 的文本。附上页面的html内容,

我使用了以下代码,

String v = driver.findElement(By.xpath("//div[1]/div[contains(@class, 'ng-scope ngRow')]//div[contains(@class, 'ngCell ng-scope col7 colt7')//"
                + "div[contains(@class, 'ngCellText ng-scope ngCellElement col7 colt7')]")).getText();

这会引发错误“表达式不是合法表达式。”代码:“12”nsresult:“0x805b0033(SyntaxError)”位置:“”]'。

当我将搜索缩小到

String v = driver.findElement(By.xpath("//div[1]/div[contains(@class, 'ng-scope ngRow')]")).getText();

它有效,我得到了特定行中的所有文本。但是,当我将它扩展到特定于第一个代码中所示的列时,我得到了错误。

html sn-p,

<div class="ng-scope ngRow even" ng-row="" ng-class="row.alternatingRowClass()" ng-click="row.toggleSelected($event)" ng-repeat="row in renderedRows" ng-style="rowStyle(row)" style="top: 0px; height: 30px;">
<div class="ngCell ng-scope pinned col0 colt0" ng-class="col.colIndex()" ng-repeat="col in renderedColumns" ng-style="{ 'cursor': row.cursor }" ng-dblclick="loadInstance(row.getProperty('incident_number'), 'ticket')" style="cursor: default;">
<div class="ngCell ng-scope col7 colt7" ng-class="col.colIndex()" ng-repeat="col in renderedColumns" ng-style="{ 'cursor': row.cursor }" ng-dblclick="loadInstance(row.getProperty('incident_number'), 'ticket')" style="cursor: default;">
<div class="ng-isolate-scope" data-target="actions_menu" context-menu="">
<div ng-style="{ 'cursor': row.cursor }" style="cursor: default;">
<div class="ngVerticalBar ngVerticalBarVisible" ng-class="{ ngVerticalBarVisible: !$last }"/>
<div ng-cell="">
<div class="ngCellText ng-scope ngCellElement col7 colt7" ng-class="col.colIndex()" tabindex="0">
<span class="ng-binding" ng-cell-text="">Closed</span>
</div>
</div>
</div>
</div>
</div>

【问题讨论】:

  • 在遇到错误之前,您的第二个 XPath 查询是您可以进入 DOM 的最远距离吗?您是否可以发布(作为代码)标记的相关部分,以便我们测试您的查询?
  • 不,第二个查询是有效的。如果我深入到第一个查询中提到的下一个级别,它将失败。
  • 带有代码的图像不可读。请用实际文本替换它们,缩进四个空格。然后,它会自动呈现为 HTML。 但是:识别HTML的相关 sn-p,不要用大量的标记轰炸我们。
  • @MathiasMüller,添加了 HTML 代码以提高可见性。

标签: java firefox xpath selenium-webdriver


【解决方案1】:

刚刚通过以下结果对其进行了测试:在粘贴的 HTML 3 中关闭 &lt;/div&gt; 丢失。 通过对 XPath 的最小调整,我得到以下结果:

<div class="ngCellText ng-scope ngCellElement col7 colt7" 
 ng-class="col.colIndex()"  tabindex="0">
 <span class="ng-binding" ng-cell-text="">Closed</span>
</div>

您只是在第一个 XPath 中缺少 ],那么它应该可以工作:

"//div[1]/div[contains(@class, 'ng-scope ngRow')]
//div[contains(@class, 'ngCell ng-scope  col7 colt7')//"
+ "div[contains(@class, 'ngCellText ng-scope ngCellElement col7 colt7')]")) ..

在第二行缺少 ],应该是:

"//div[1]/div[contains(@class, 'ng-scope ngRow')]
//div[contains(@class, 'ngCell ng-scope  col7 colt7')]//"

由于我只是使用 XPath-Tester 进行检查并且没有您正在处理的相同设置,因此您应该尝试一下。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    相关资源
    最近更新 更多