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

使用Python Selenium WebDriver获取Lichess用户活跃时间报错求助

解决Selenium获取Lichess用户活跃时间的问题

问题分析

你之前的代码主要有三个问题:

  • 元素定位不精准:By.CLASS_NAME="time"会匹配页面中所有class为time的元素,容易定位到错误节点
  • 属性调用错误:get_attribute("set")是无效操作,你要的「9 months ago」是time标签的文本内容,并非某个属性值
  • 未等待元素加载:页面还没渲染完成就执行查找操作,大概率会触发NoSuchElementException

修正后的代码

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

def function1(nick_hraca):
    driver = webdriver.Chrome()
    base_url = f"https://lichess.org/@/{nick_hraca}"

    driver.get(base_url)
    # 显式等待元素加载,最长等待10秒
    wait = WebDriverWait(driver, 10)
    
    # 精准定位用户活跃时间的time标签:通过父元素特征+层级关系定位,避免依赖固定索引
    activity = wait.until(EC.presence_of_element_located(
        (By.XPATH, '//div[@id="us_profile"]//p[contains(text(), "Last seen")]/time')
    ))
    # 获取显示的文本内容,即你需要的「9 months ago」
    print(activity.text)

    # 同样用显式等待定位游戏数元素
    games = wait.until(EC.presence_of_element_located(
        (By.XPATH, '//main//div[5]/a[2]')
    ))
    print(games.text)

    driver.quit()

补充说明

  • 用WebDriverWait显式等待替代time.sleep(),既能保证元素加载完成,又不会浪费不必要的等待时间
  • XPath定位时使用contains(text(), "Last seen"),可以避免依赖固定的p标签索引(比如p[2]),防止页面结构微调导致定位失效
  • 如果需要获取time标签的原始时间戳(比如datetime属性里的ISO格式时间),可以调用activity.get_attribute("datetime")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:27:39