如何在Python版Selenium中排除指定类名元素?
解决方法:排除带有
card--live类的赛事元素 问题根源
你当前用By.CLASS_NAME选择card.ng-star-inserted是无效的——CLASS_NAME不支持多类名组合,而直播赛事元素同时包含card、card--live、ng-star-inserted三类,所以你的选择器会把直播和非直播赛事全部选中。
可行方案
方案1:用CSS选择器精准筛选(推荐)
通过CSS选择器选中包含card和ng-star-inserted类,但不包含card--live类的元素:
website = 'https://winline.ru/stavki/sport/futbol' driver.get(website) team1 = [] team2 = [] driver.implicitly_wait(3) # 核心:用:not()排除带card--live类的元素 table_winline_1 = driver.find_elements(By.CSS_SELECTOR, "div.card.ng-star-inserted:not(.card--live)") for match in table_winline_1: team1.append(match.find_element(By.XPATH, './div[1]/a/div/div[1]').text) team2.append(match.find_element(By.XPATH, './div[1]/a/div/div[2]').text) print(team1) print(team2)
方案2:遍历后手动过滤
如果CSS选择器仍有问题,可以先获取所有card类元素,再手动剔除带card--live类的项:
website = 'https://winline.ru/stavki/sport/futbol' driver.get(website) team1 = [] team2 = [] driver.implicitly_wait(3) all_matches = driver.find_elements(By.CLASS_NAME, "card") for match in all_matches: match_classes = match.get_attribute("class") # 只保留非直播且带ng-star-inserted类的元素 if "card--live" not in match_classes and "ng-star-inserted" in match_classes: team1.append(match.find_element(By.XPATH, './div[1]/a/div/div[1]').text) team2.append(match.find_element(By.XPATH, './div[1]/a/div/div[2]').text) print(team1) print(team2)
额外提示
By.CLASS_NAME只能传入单个类名,不能用.分隔多类,这是你之前出错的关键。- 若页面加载慢,建议把
implicitly_wait换成显式等待,确保元素完全加载:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待10秒,直到目标元素加载完成 table_winline_1 = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.card.ng-star-inserted:not(.card--live)")) )
内容的提问来源于stack exchange,提问作者AlexReed
相关产品推荐
相关产品推荐

