如何通过 css 中的文本而不是 xpath 正确识别选择器

How do I properly identify a selector by its text in css instead of xpath

当我设置一些简单的时候html

<html>
  <head>
    <title>Simple Site</title>
  </head>
  <body>
    <form>
      <label>Name:</label><input type="text"></form><br/>
      <label>Phone:</label><input type="text">
    </form>
    <div>happy</div>
    <div>angry</div> 
    <div>sad</div>
  </body>
</html>

我试图通过其文本指定 div,但无法

 div[@text='happy']              #nope
 html body div[@text='angry']    #nope
 html body div:contains('angry') #nope
 html body div[text='angry']     #nope

我错过了什么?

使用以下代码:

 div[type='happy']{
   background-color:red;
 }   
<form>
    <label>Name:</label><input type="text"></form><br/>
<label>Phone:</label><input type="text">
</form>
<div type="happy">happy</div>
<div>angry</div>
<div>sad</div>

CSS 无法匹配元素的文本内容,但 Capybaras find 提供了一个 text 选项来按文本内容进行过滤。它需要一个字符串或一个正则表达式

angry_div = find(:css, 'div', text: 'angry') # The :css can be omitted if Capybara.default_selector = :css (which it is by default)