如何用Beautiful Soup精准匹配仅含sp-betbutton类的按钮?
解决精准匹配单一类名元素的问题
方法1:BeautifulSoup 中使用 CSS 选择器精确匹配
用[class="sp-betbutton"]这个CSS选择器,它会严格匹配class属性值恰好等于"sp-betbutton"的元素,完全排除带有额外类名的按钮。
示例代码:
from bs4 import BeautifulSoup # 假设已通过Selenium获取页面源码并生成soup对象 odds_buttons = soup.select('[class="sp-betbutton"]') # 遍历处理匹配到的按钮 for button in odds_buttons: odds = button.get_text(strip=True) # 后续关联处理赛马编号、名称等数据
方法2:Selenium 阶段直接精准定位
如果不想依赖BeautifulSoup中转,在Selenium里也能用同样的CSS选择器直接过滤:
from selenium.webdriver.common.by import By # 定位仅包含sp-betbutton单一类名的元素 odds_buttons = driver.find_elements(By.CSS_SELECTOR, '[class="sp-betbutton"]') for button in odds_buttons: odds = button.text.strip() # 后续业务逻辑
出错原因说明
你之前用的find_all(class_="sp-betbutton")或Selenium的find_elements(By.CLASS_NAME, "sp-betbutton")属于包含匹配——只要元素的class列表里有"sp-betbutton"就会被选中,不管是否附带其他类名,这才导致带sp-betbutton--enhanced的按钮混入,造成数据错位。
内容的提问来源于stack exchange,提问作者tom bannister
相关产品推荐
相关产品推荐

