简体   繁体   English

使用CSS选择具有相同类名的多个元素

[英]Selecting multiple elements with same classname using CSS

So i have a list of questions on the home page like this:所以我在主页上有一个问题列表,如下所示:

<div id="question-summary-36771853" class="question-summary narrow">
<div id="question-summary-36772065" class="question-summary narrow">
<div id="question-summary-36772003" class="question-summary narrow">
<div id="question-summary-36772259" class="question-summary narrow">
<div id="question-summary-36772257" class="question-summary narrow">
<div id="question-summary-36772256" class="question-summary narrow">
<div id="question-summary-36772253" class="question-summary narrow"> 

now the id changes everytime the page is refreshed.现在每次刷新页面时 id 都会更改。 I want to know how can i use CSS selector to capture just the first 5 questions.我想知道如何使用 CSS 选择器来捕获前 5 个问题。

You can partially match the id using the "starts-with" or "contains" notation:您可以使用“starts-with”或“contains”符号部分匹配id

div[id^="question-summary-"]

Or, you can check the class instead of id:或者,您可以检查类而不是 id:

div.question-summary

As for limiting it to 5 first elements only, you can use the "findElements" method of your selenium language bindings and slice the result.至于将其限制为仅 5 个第一个元素,您可以使用 selenium 语言绑定的“findElements”方法并对结果进行切片。 Example in Python: Python 中的示例:

questions = driver.find_elements_by_css_selector('div[id^="question-summary-"]')
first_5_questions = questions[:5]

If you'll like a CSS only based way to do it, you could use :nth-child pseudo-selector, to select only the first 5 elements.如果您喜欢仅基于 CSS 的方法,您可以使用:nth-child伪选择器,只选择前 5 个元素。 It's a little bit manual, but can be achieved with CSS like this:这有点手动,但可以使用 CSS 来实现,如下所示:

.question-summary:nth-child(1),
.question-summary:nth-child(2),
.question-summary:nth-child(3),
.question-summary:nth-child(4),
.question-summary:nth-child(5) {
   /* your style goes here */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM