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

使用Selenium爬取单条网页记录返回空结果,求排查逻辑问题

问题分析与修复方案

问题原因

  • 元素定位层级错误:你通过workDetails容器查找work-title元素,但实际页面中work-title并不在该容器的子节点范围内,导致find_element无法定位到目标元素,最终title变量无内容。
  • 等待条件不合适:presence_of_all_elements_located仅保证元素存在于DOM中,但元素可能还未渲染出文本内容,直接获取.text会返回空值。
  • 冗余代码:页面中只有一个目标标题,无需声明global变量,也不需要循环遍历items列表。

修复后的代码

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

driver = webdriver.Chrome(executable_path='chromedriver.exe')
url = "https://openlibrary.org/works/OL7960560W/Eyewitness?edition=ia%3Acowboy0000murd_y0x0"
driver.get(url)
wait = WebDriverWait(driver, 10)

# 直接等待标题元素可见并获取文本
title = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'work-title'))).text

print("title = ", title)
driver.quit()  # 执行完毕后关闭浏览器释放资源

额外优化建议

  • 移除不必要的global声明:局部作用域内定义变量即可满足需求,全局变量会增加代码复杂度。
  • 延长等待超时:将等待时间从5秒调整为10秒,适配网络延迟场景。
  • 强制关闭浏览器:脚本结束时调用driver.quit(),避免残留浏览器进程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:10:51