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

Python Selenium操作新浪财经搜索栏失效问题求助

问题分析与修复方案

代码中的核心问题

  • 未初始化WebDriver实例:仅配置了Chrome选项,但没有创建driver对象,直接调用driver.get(url)会触发异常,这是浏览器异常关闭的关键原因。
  • 语法错误:send_keys('sz111973'))多了一个右括号,会直接导致代码运行失败。
  • 等待逻辑不严谨:仅等待搜索框“存在”,未确保元素可交互;页面加载受反爬机制影响,缺少必要的操作延迟。

修正后的代码

import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 配置Chrome浏览器选项
options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-notification")
options.add_argument("--disable-infobars")
options.add_experimental_option('excludeSwitches', ['enable-logging'])

# 初始化WebDriver(之前缺失的关键步骤)
driver = webdriver.Chrome(options=options)
driver.maximize_window()  # 最大化窗口避免元素被遮挡

url = 'https://vip.stock.finance.sina.com.cn/mkt/#hs_z'
driver.get(url)

# 等待搜索框可交互,而非仅存在
wait = WebDriverWait(driver, 15)
search_box = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="inputSuggest"]')))

# 模拟人类操作节奏,加入随机延迟
search_box.clear()
time.sleep(random.uniform(0.4, 1.2))
search_box.send_keys('sz111973')

# 等待搜索按钮可交互后点击
search_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="SSForm"]/input[3]')))
time.sleep(random.uniform(0.3, 0.8))
search_btn.click()

# 保留浏览器窗口,避免执行后立即关闭
input("操作完成,按回车键关闭浏览器...")
driver.quit()

额外优化建议

  • 异常捕获与排查:将核心操作包裹在try-except块中,方便定位错误,还可保存错误截图辅助排查:
    try:
        # 上述核心操作代码
    except Exception as e:
        print(f"执行出错: {e}")
        driver.save_screenshot('error_screenshot.png')
    finally:
        driver.quit()
    
  • 页面加载验证:可添加页面完全加载的等待逻辑,避免因页面未加载完成导致元素定位失败:
    wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:31:21