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

如何遍历列获取所有球员的href?(基于Selenium实现)

解决方法

嘿,我来帮你搞定这个问题!你的代码现在只能拿到单个href,主要是两个小问题导致的:

  • 重复初始化了浏览器对象(那行重复的browser = webdriver.Chrome(...)可以删掉)
  • 使用了单数形式的find_element_by_class_name,它只会返回页面中匹配的第一个元素,你需要用复数形式的find_elements_by_class_name来获取所有匹配的元素集合

下面是修正后的完整代码,我标注了关键修改点:

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

# 移除重复的浏览器初始化语句
browser = webdriver.Chrome("/ProgramData/chocolatey/bin/chromedriver.exe")
browser.get("https://rotogrinders.com/projected-stats/mlb-hitter?site=fanduel")

timeout = 20
try:
    # 改为等待所有player-popup元素加载完成,更稳妥
    WebDriverWait(browser, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'player-popup')))
except TimeoutException:
    print("Timed out waiting for page to load")
    browser.quit()

# 用复数形式的find_elements获取所有目标元素
players_links = browser.find_elements_by_class_name('player-popup')

# 遍历每个元素,提取href属性
for link in players_links:
    href = link.get_attribute("href")
    if href:  # 过滤空值,避免打印无效内容
        print(href)

# 程序结束后关闭浏览器进程
browser.quit()

关键修改细节:

  • 删掉了重复的浏览器初始化代码,避免不必要的资源占用
  • 把等待条件从visibility_of_element_located换成visibility_of_all_elements_located,确保所有球员链接都加载完成后再提取,防止漏抓
  • 用find_elements_by_class_name(复数)替代单数方法,获取页面中所有带player-popup类的元素
  • 增加循环遍历每个元素,逐个提取href,并加入空值判断提升鲁棒性
  • 最后添加browser.quit(),确保浏览器进程正常关闭

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:40:57