selenium - 如何使用XPath在特定表单元格内获取值

标签 selenium xpath behat acceptance-testing gherkin

我正在学习如何使用Behat / Mink和Selenium编写验收测试,并且需要验证特定表格单元的值。我发现必须使用xpath来执行此操作,但是我无法弄清楚确切的语法。下表如下:

enter image description here

的HTML:

<table class="admintable generaltable" id="relationships">
<thead>
...
</tr>
</thead>
<tbody><tr class="r0 lastrow">
<td class="leftalign cell c0" style="">Cohort 1</td>
<td class="leftalign cell c1" style="">0</td>
<td class="leftalign cell c2" style="">Non-editing teacher</td>
<td class="centeralign cell c3" style="">No</td>
<td class="leftalign cell c4" style="">No</td>
<td class="leftalign cell c5 lastcol" style=""><a href="http://150.162.242.121/mariana/unasus-cp/local/relationship/edit_cohort.php?relationshipcohortid=1&amp;delete=1"><img src="http://150.162.242.121/mariana/unasus-cp/theme/image.php/standard/core/1445875205/t/delete" alt="Delete" title="Delete" class="iconsmall" /></a> <a href="http://150.162.242.121/mariana/unasus-cp/local/relationship/edit_cohort.php?relationshipcohortid=1"><img src="http://150.162.242.121/mariana/unasus-cp/theme/image.php/standard/core/1445875205/t/edit" alt="Edit" title="Edit" class="iconsmall" /></a></td>
</tr>
</tbody>
</table>


我要写的语句是:

Then I should see "No" in the "???" "css_element"


我应该如何准确地写出该语句,以指定我希望“否”部分中“Inscriçãoemváriosgrupos”下的第一个“否”。

编辑:我最初犯了一个错误,我应该使用“ xpath_element”作为选择器,而不是“ css_element”

最佳答案

我假设Inscrição em vários grupos文本始终出现在第4列中。为此,编写XPath非常容易,因为我们可以直接使用索引。

//table[@id='relationships']/tbody/tr[1]/td[4]


如果标题列的列号不同,则必须找到Inscrição em vários grupos标题的索引(列号),然后使用它来找到对应的值列。

-- the below code will get you the index of the heading column
count(//thead//tr/th[.='Inscrição em vários grupo']/preceding-sibling::*)+1

-- use this index to find the corresponding value
//table[@id='relationships']/tbody/tr[1]/td[count(//thead//tr/th[.='Inscrição em vários grupo']/preceding-sibling::*)+1]


注意:索引从1开始而不是0

在以下链接中,behat中的语法似乎如下:

How to assert that a text only exists 1 time in Mink

https://stackoverflow.com/questions/32202047/could-not-find-element-with-xpath-in-behat-mink

$session = $this->getMainContext()->getSession();
$element = $session->getPage()->find(
        'xpath',
        $session->getSelectorsHandler()->selectorToXpath('xpath', '//table[@id='relationships']/tbody/tr[1]/td[4]');
$elementText = $element->getText();

if ($elementText != 'no') {
    throw new Exception('Value us not correct');
}

关于selenium - 如何使用XPath在特定表单元格内获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394754/

相关文章:

java - Selenium 不使用 geckodriver 10.0 打开 firefox - 无法访问的浏览器异常

.net - 获取与Webbrowser文档中的XPath表达式匹配的所有元素

xml - XSLT 1.0 - 分组 xml 元素

python - 即使我正在迭代行, Selenium 也会选择表中的第一行

selenium-webdriver - 测试输入字段是否获得焦点

php - 贝哈特 3 : How to get profile name inside FeatureContext

c# - 通过windows服务打开浏览器渲染和截图selenium .Net中的webgl页面

java - 比较列表 WebElement 与字符串数组

symfony - 媒体文件行为测试

python - 无法从弹出窗口中抓取文本