Selenium Firefox驱动执行搜索后返回空列表问题咨询
解决Selenium获取DuckDuckGo搜索结果为空的问题
Hey Kate, let's break down why you're getting that empty [] when trying to grab search results—this is a super common web scraping hiccup, so no need to stress!
核心问题有两个:
- 页面加载跟不上代码执行速度:Selenium执行命令的速度很快,往往在搜索结果还没完全加载出来时,就已经开始查找元素了,自然找不到内容。
- 元素定位的class名称错误:DuckDuckGo的页面结构已经更新,你代码里用的
result类名,现在已经不是搜索结果条目的对应类名了。
修正后的代码示例
这里是修复两个问题后的可靠代码:
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 如果需要启用无头模式,取消下方注释 # from selenium.webdriver.firefox.options import Options # options = Options() # options.add_argument("--headless") # driver = webdriver.Firefox(options=options) driver = webdriver.Firefox() driver.get("https://duckduckgo.com") # 定位搜索框并执行搜索 search_form = driver.find_element(By.ID, "search_form_input_homepage") search_form.clear() search_form.send_keys("python jobs remote") search_form.submit() # 关键:用显式等待等待结果加载完成(最多等10秒) # 当前DuckDuckGo搜索结果条目的类名为"result__body" results = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CLASS_NAME, "result__body")) ) # 打印第一个结果的文本内容验证 print(results[0].text) driver.close()
几个重要细节说明:
- 用显式等待代替直接查找:
WebDriverWait会让Selenium最多等待10秒,直到目标元素出现在页面上,比硬编码time.sleep()更灵活可靠。 - 更新元素定位器:我查了当前DuckDuckGo的页面结构,每个搜索结果条目都包裹在
result__body类的元素里——这才是你应该定位的目标。 - 替换弃用的旧方法:新版Selenium里,
find_element_by_id这类方法已经被弃用,推荐使用find_element(By.ID, "元素ID")这种标准化写法。
如果还是有问题,你可以右键点击FireFox里的搜索结果,选择「检查」,直接查看元素的类名确认——网站UI时不时会更新,自己核对最稳妥!
内容的提问来源于stack exchange,提问作者KateMac
相关产品推荐
相关产品推荐

