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

Selenium Python:获取网页data-original-title属性返回None的解决方法

解决球员国籍获取问题

方法一:优化Selenium获取逻辑

  1. 等待元素完全加载
    大概率是你获取元素时,data-original-title属性还未完成渲染,改用显式等待确保元素就绪:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 等待元素可见,超时10秒
    country_element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, xpath_country))
    )
    country = country_element.get_attribute('data-original-title')
    
  2. 用JavaScript直接读取属性
    部分动态生成的属性无法通过Selenium常规方法获取,试试执行JS脚本:

    country = driver.execute_script("return arguments[0].getAttribute('data-original-title');", country_element)
    
  3. 模拟鼠标悬停触发tooltip
    data-original-title是tooltip专属属性,可能需要鼠标悬停后才会赋值,模拟悬停操作:

    from selenium.webdriver.common.action_chains import ActionChains
    
    action = ActionChains(driver)
    action.move_to_element(country_element).perform()
    # 悬停后再获取属性
    country = country_element.get_attribute('data-original-title')
    

方法二:改用Requests+BeautifulSoup(更高效)

如果不需要模拟浏览器交互,直接请求页面解析更轻量化:

import requests
from bs4 import BeautifulSoup

url = "https://wefut.com/player-database/22"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

# 遍历所有带tooltip的国籍链接
country_links = soup.find_all('a', rel='tooltip')
for link in country_links:
    country = link.get('data-original-title')
    if country:
        print(country)

额外排查点

  • 核对你的xpath_country定位表达式,确认没有定位到错误元素
  • 打开页面源码(F12)检查目标元素的data-original-title是否真实存在,部分网站会通过异步接口动态生成属性,此时可直接抓接口数据获取国籍信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:15:42