跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

如何在 Selenium(Python)中精确排除含特定类名的元素

本文介绍如何使用 XPath 的 not(contains(@class, ...)) 组合条件,在 Selenium 中精准定位不含 card--live 类的非直播赛事卡片,避免误抓直播事件数据。 本文介绍如何使用 xpath 的 `not(contains(@class, ...))` 组合条件,在 selenium 中精准定位不含 `card--live` 类的非直播赛事卡片,避免误抓直播事件数据。 在 Web 自动化与数据采集场景中,仅靠 By.CLASS_NAME 或简单 CSS 选择器往往无法满足精细化筛选需求——尤其当目标元素共享基础类名(如 "card ng-star-inserted"),而需排除带额外修饰类(如 "card--live")的变体时。此时,XPath 提供了强大且语义清晰的逻辑表达能力。 ✅ 推荐解决方案:使用复合 XPath 定位非直播卡片 应避免使用 By.CLASS_NAME(它不支持多类名精确匹配或排除),改用 XPath 表达式,同时满足两个条件: 元素的 class 属性包含 "card" 和 "ng-star-inserted"(注意空格分隔); 且 不包含 "card--live" 字符串。
from selenium.webdriver.common.by import By # ✅ 正确:定位 class 同时包含 "card" 和 "ng-star-inserted",但不含 "card--live" table_winline_1 = driver.find_elements( By.XPATH, '//div[contains(@class, "card") and contains(@class, "ng-star-inserted") and not(contains(@class, "card--live"))]' )
⚠️ 注意事项: ❌ 错误写法 //div[contains(@class, "card ng-star-inserted")] —— contains() 是子字符串匹配,会错误匹配 "card--live ng-star-inserted"(因该字符串包含 "card ng-star-inserted" 的部分字符序列); ✅ 正确思路是 分别校验每个独立类名是否存在 ,再用 not(contains(...)) 排除干扰项; 若 HTML 中 class 值顺序不固定(如 "ng-star-inserted card card--live"),上述写法依然健壮,因其基于内容而非位置判断; 首次执行前建议添加显式等待(如 WebDriverWait + presence_of_element_located),确保 DOM 渲染完成,避免空列表问题。 ? 进阶提示:若后续需进一步提升稳定性,可结合 data-* 属性或更稳定的父级结构路径(例如定位到
下的卡片),但当前 XPath 已能准确解决“排除 live 类”的核心诉求。 最终,你的完整采集逻辑可优化为: Python 3.14.3 微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。 下载 立即学习 “ Python免费学习笔记(深入) ”;
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver.get('https://winline.ru/stavki/sport/futbol') wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.XPATH, '//div[contains(@class, "card") and contains(@class, "ng-star-inserted")]'))) matches = driver.find_elements( By.XPATH, '//div[contains(@class, "card") and contains(@class, "ng-star-inserted") and not(contains(@class, "card--live"))]' ) team1, team2 = [], [] for match in matches: try: t1 = match.find_element(By.XPATH, './div[1]/a/div/div[1]').text.strip() t2 = match.find_element(By.XPATH, './div[1]/a/div/div[2]').text.strip() team1.append(t1) team2.append(t2) except Exception as e: continue # 跳过结构异常的卡片,增强鲁棒性 print("非直播赛事队伍1:", team1) print("非直播赛事队伍2:", team2)
该方案兼顾准确性、可读性与工程健壮性,是处理动态类名过滤的推荐实践。

相关文章