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

Selenium爬取元素定位失败:无法获取网页时间戳

问题排查与解决建议

可能的原因及对应解决方法:

  • 元素未完全加载
    页面可能处于异步加载状态,直接调用find_elements会返回空列表。添加显式等待确保元素加载完成:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    # 等待父元素加载
    details = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "stories-list"))
    )
    # 等待目标子元素全部加载
    res = WebDriverWait(details, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, "./div[@class='b-gray-800']"))
    )
    for items in res:
        print(items.get_attribute('data-story-timestamp'))
    
  • class属性匹配问题
    若目标元素后续可能新增其他class值(如b-gray-800 active),精确匹配会失效,改用包含匹配:

    res = details.find_elements("xpath", "./div[contains(@class, 'b-gray-800')]")
    
  • 元素位于iframe内
    如果stories-list嵌套在iframe中,需先切换到iframe再定位:

    # 替换为实际iframe的定位标识(id/name/索引)
    iframe = driver.find_element(By.ID, "目标iframe的id")
    driver.switch_to.frame(iframe)
    # 执行原定位代码
    details = driver.find_element("xpath","//div[@id='stories-list']")
    res = details.find_elements("xpath","./div[@class = 'b-gray-800']")
    for items in res:
        print(items.get_attribute('data-story-timestamp'))
    # 操作完成后切回主文档
    driver.switch_to.default_content()
    
  • 简化XPath写法
    直接从根节点定位目标元素,避免相对路径可能出现的问题:

    res = driver.find_elements("xpath", "//div[@id='stories-list']/div[@class='b-gray-800']")
    

内容的提问来源于stack exchange,提问作者Dirk De croost

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:05:20