You need to enable JavaScript to run this app. Selenium无法爬取网页全部内容,无法获取playersList类下li元素如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Selenium无法爬取网页全部内容,无法获取playersList类下li元素如何解决?

问题根因
  • 动态渲染等待缺失:球员列表由JS异步加载,driver.get()执行完成时DOM还没渲染出目标节点,直接查找必然返回空
  • Selenium API兼容性问题:4.x及以上版本已废弃find_element_by_*系列方法,调用时会抛出异常或返回无效结果
  • 无头模式反爬拦截:默认的无头浏览器UA会被部分网站识别拦截,返回无有效内容的空白页
修复后可运行代码
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
import csv
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 常量配置
opts = Options()
opts.add_argument("--headless=new") # 用新版无头模式,反爬识别概率更低
opts.add_argument('--ignore-certificate-errors')
opts.add_argument('--incognito')
opts.page_load_strategy = 'normal'
# 伪造正常浏览器UA,绕过基础反爬
opts.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')

# 第一步:获取所有球队信息
page = "https://www.iplt20.com/teams"
uClient = uReq(page)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html,"html.parser")
teams =[]
ul = page_soup.find("ul",{"class":"content-grid"})
lis  = ul.findAll("li",{"class":"team-card-grid__item"})
for li in lis:
    l=[]
    l.append(li.find("h3",{"class":"card__title"}).text.strip())
    try:
        l.append(li.find("div",{"class":"team-card__wins"}).text.strip())
    except:
        l.append('')
    l.append("https://www.iplt20.com"+li.find("a",{"class":"card"})["href"]+"/squad")
    teams.append(l)

# 第二步:爬取各队球员信息
for team in teams:
    team_page = team[2]
    driver = webdriver.Chrome(options=opts)
    try:
        driver.get(team_page)
        # 显式等待10秒,直到球员列表节点加载完成
        player_list = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "playersList"))
        )
        players = player_list.find_elements(By.TAG_NAME, "li")
        print(f"球队:{team[0]},球员数量:{len(players)}")
        for player in players:
            print(player.text.strip())
        driver.save_screenshot(f"{team[0]}.png")
    except Exception as e:
        print(f"爬取{team[0]}失败:{str(e)}")
    finally:
        driver.quit() # 关闭浏览器进程,避免资源泄漏
    break
替代实现方案
  • 接口直爬:打开浏览器开发者工具的网络面板,筛选XHR/ Fetch请求,可找到球队阵容的后端数据接口,直接请求接口获取JSON格式数据,无需解析DOM,效率和稳定性更高
  • Playwright替代Selenium:内置自动等待机制,无需手动写等待逻辑,浏览器指纹伪造能力更强,更适合复杂动态网站爬取
学习参考资料
  • Selenium核心知识点:重点掌握显式等待、元素定位、无头模式配置、反爬绕过四个模块
  • 动态网页爬取核心:理解异步渲染原理、掌握浏览器抓包方法、熟悉常见的前端渲染逻辑
  • 爬虫通用技巧:请求头配置、IP代理使用、浏览器指纹修改、异常重试机制设计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 07:06:08