从DOM中选择元素
在页面内容上,我有多张卡片组织成一个网格
On my page contents, I have multiple cards organized as a grid
__________________
| ____ ____ |
| | | | | |
| | | | | |
| |____| |____| |
| |
| ____ ____ |
| | | | | |
| | | | | |
| |____| |____| |
|__________________|
我的问题是每个卡片容器都具有相同的类,我想在容器内选择一个不同的元素.示例:
My issue is that each card container has the same class, and I want to select a distinct element inside a container. Example:
<div class="parent-container">
<div class="container">
<h2> Distinct title 1 </h2>
</div>
<div class="container">
<div class="another-container">
<button>
<span> Click Here! </span>
</button>
</div>
</div>
</div>
[repeat X times]
或使用DOM树
. Parent div
|_ child div
| |_ <h2> Distinct title 3 </h2>
|
|_ child div
|_ grandchild div
|_ button
|_ <span> Click Here! </span>
因此,假设我想在第三个容器上选择一个元素.选择器查询会如何?
So, supposedly I want to select an element on the third container. How would the selector query be?
基于@lostlemon的答案,我的查询如下:
Based on @lostlemon answer, my query is the following:
await t
.click(Selector('span')
.parent(3)
.child('h2')
.withExactText('Distinct title 3'));
在这种情况下,如果您总是要选择第三个容器,则可以使用nth-child
或nth-of-type
:>
If you always want to select the third container in this scenario, you could use nth-child
or nth-of-type
:
await t.click('div:nth-child(3) > span');
如果您需要单击基于标题的跨度,请尝试以下操作:
If you need to click on the span based on title, try this:
await t
.click(Selector('span').parent('.parent-container')
.child('h2').withExactText('Distinct title 3');
-
如果所有
-
.withText()
- 如果您要定位容器类,请确保您的父选择器正在尝试查找类而不是元素
-
.find()
寻找一个元素,因此它与不同的标题文本不匹配 -
.withText()
can be removed if all the<span>
s have the same text - make sure your parent selector is trying to find the class and not an element if you're targeting the container class
-
.find()
looks for an element, so it wouldn't match the distinct title text
<span>
具有相同的文本,则可以删除