我需要CSS选择器来选择包含给定文本的元素

时间:2016-04-26 10:28:43

标签: html css selenium selenium-webdriver

行:

<div class="btn btn-second-in-pair-not-desired btn-tall">Clear search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall">Raw Search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall">Basic Search</div>
<div class="btn btn-primary-stand-alone btn-tall search-btn">Search</div>

这是我到目前为止所尝试的 - &#34; .btn:包含(&#39;清除搜索&#39;)&#34;但是硒无法捕捉它

6 个答案:

答案 0 :(得分:1)

CSS Selector不再支持:contains()。您必须使用XPath "//div[text()='Clear search']"

答案 1 :(得分:0)

我不认为css支持按html元素的内容进行搜索。

为什么不尝试:

<div class="btn btn-second-in-pair-not-desired btn-tall clear">Clear search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall raw">Raw Search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall basic">Basic Search</div>
<div class="btn btn-primary-stand-alone btn-tall search-btn">Search</div>

然后选择通过:

.btn{
  color:red;
}

.clear, .raw, .basic, .search-btn{
  color:blue;
}

或者您可以随时尝试使用ID

<div id="search">Search</div>

选择

#search{
 ...
}

答案 2 :(得分:0)

如果你使用Selenium,它也接受XPATH字符串,在某些情况下,它有时比CSS选择器更灵活。因为我也非常懒,所以我发现你可以右键单击DevTools的Elements视图中的标签和&#34;复制&gt;复制XPath&#34;

webDriver.findElement(
  By.xpath(
    "//div[text()='Clear search']"
  )
).click();

答案 3 :(得分:0)

你不能根据内容改变班级吗?

<?php 
$content = $your_content_from_database;
$arr_content = explode(" ", $content);
$first = $arr_content[0];
echo '<div class="btn btn-second-in-pair-not-desired btn-tall clear" data-content="'.$first.'">'. $content. '</div>' ; ?>

和CSS

[data-content="Clear"]{
color:red;
}

答案 4 :(得分:0)

您好,根据您在问题中提供的来源,您可以使用如下的css选择器来识别元素

// take everything inside the list for div with same class
List<WebElement> mycsselements =  driver.findElements(By.cssSelector(".btn.btn-second-in-pair-not-desired.btn-tall"));
System.out.println("Size of the div elements with same class name : " + mycsselements.size());
// printing value one by one 
System.out.println("First value is "  + mycsselements.get(0).getText());
System.out.println("Second value is " + mycsselements.get(1).getText());
System.out.println("Third value is "  + mycsselements.get(2).getText());

// and for the last one do it like below

System.out.println("Last value is " + driver.findElement(By.cssSelector(".btn.btn-primary-stand-alone.btn-tall.search-btn")).getText());

,输出为:

Size of the div elements with same class name : 3
First value is Clear search
Second value is Raw Search
Third value is Basic Search
Last value is Search

希望这有助于你

答案 5 :(得分:0)

用户在css代码下面:

css=div:contains('Clear search')

更多详情请点击链接:SauceLab