使用 CSS 选择器通过 selenium 访问特定的表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4494708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:21:20  来源:igfitidea点击:

Using CSS selectors to access specific table rows with selenium

cssseleniumcss-selectors

提问by wierddemon

If I have the following HTML:

如果我有以下 HTML:

<tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

我将如何使用带有 Selenium 的 CSS 选择器来访问项目 4(或我想要的任何项目)?

回答by Flack

You can use nth-child selector:

您可以使用第 n 个子选择器:

#items tr:nth-child(4) {color:#F00;}

Live example: https://jsfiddle.net/7ow15mv2/1/

实例:https: //jsfiddle.net/7ow15mv2/1/

But no idea if it works with Selenium.

但不知道它是否适用于 Selenium。

But according to docs it should.

但根据文档它应该。

Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).

目前 css 选择器定位器支持所有 css1、css2 和 css3 选择器,除了 css3 中的命名空间,一些伪类(:nth-​​of-type,:nth-​​last-of-type,:first-of-type,:last-of- type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) 和伪元素(::first-line, ::first-letter, ::selection, ::before, ::后)。

回答by Anthony

you can try this for searching by any inner text

您可以尝试通过任何内部文本进行搜索

css=td:contains('Item 4')

found this helpful: http://saucelabs.com/blog/index.php/2010/01/selenium-totw-css-selectors-in-selenium-demystified/

发现这很有帮助:http: //saucelabs.com/blog/index.php/2010/01/selenium-totw-css-selectors-in-selenium-demystified/

回答by Mitro

Do you want to select by content ("Item 4")? By Position (the 4st row)? Or is <tr id="foo">and selecting tr#foo>td an option?

是否要按内容选择(“项目 4”)?按位置(第 4 行)?或者是<tr id="foo">选择 tr#foo>td 一个选项?

回答by farheen

selenium.getText("css=table>tbody[id=items]>tr:nth-child(3)>td(3)");

回答by Brian O'Neill

You could use xpath to find it in a number of different ways but the easiest is:

您可以使用 xpath 以多种不同的方式找到它,但最简单的是:

//td[text()='Item 4']