You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不带双引号的CSS属性选择器合规吗?还是Selenium特有行为?

CSS选择器属性值无引号写法的标准说明

核心结论

无引号的img[alt=Google]写法完全符合CSS官方标准,并非Selenium的特殊处理。

具体规则

CSS规范对属性选择器的属性值有明确规定:

  • 当属性值是标识符(仅由字母、下划线、连字符、数字组成,且不以数字开头)时,属性值可以省略单/双引号。Google属于纯字母组成的合法标识符,满足这个条件,因此无需引号包裹也能被正确解析。
  • 若属性值包含空格、特殊符号(如!、@、空格等),或者以数字开头,则必须用单引号或双引号包裹,比如img[alt="Google Search"]、img[alt='123-icon']这类场景。

为什么Selenium两种写法都支持

Selenium本身不会修改或额外处理CSS选择器,它只是将选择器直接传递给浏览器(这里是Chrome)的渲染引擎解析。而Chrome的引擎完全遵循CSS规范,所以两种写法都能正常匹配元素。

验证代码(可在Selenium 4.22.0 + Python 3.12.4环境运行)

from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = ChromeOptions()
options.add_argument("--headless")

selectors = [
    'img[alt=Google]',
    'img[alt="Google"]'
]

with webdriver.Chrome(options=options) as driver:
    driver.get("https://www.google.com")
    wait = WebDriverWait(driver, 5)
    for selector in selectors:
        t = By.CSS_SELECTOR, selector
        wait.until(EC.presence_of_element_located(t))

内容的提问来源于stack exchange,提问作者jackal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:39:57