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

Python Selenium网页登录爬取问题求助:send_keys失效、耗时过长

问题分析与修复方案

核心问题排查

  1. 不必要的超长等待:代码里time.sleep(100)强制等待100秒,完全是浪费时间,网页加载完成后仍在无效等待。
  2. 过时的元素定位语法:driver.find_element_by_name(name="j_password")是Selenium 3及更早版本的写法,Selenium 4+已废弃,会导致语法错误。
  3. 未处理元素加载延迟:直接查找元素可能遇到元素未渲染完成的情况,导致send_keys失败。
  4. 终端的DevTools listening on和TensorFlow提示是Chrome浏览器的日志输出,不是代码执行失败的原因,可忽略或通过配置消除。

修复后的完整代码

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
from selenium.webdriver.chrome.options import Options

# 配置Chrome关闭无关日志,消除终端冗余提示
chrome_options = Options()
chrome_options.add_argument("--log-level=3")
chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])

username = "rahbar"
password = "password"

print("something before scrape")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://plp.irbroker.com/index.do")
driver.maximize_window()

# 显式等待用户名输入框可交互,最多等待10秒
wait = WebDriverWait(driver, 10)
username_input = wait.until(EC.element_to_be_clickable((By.NAME, "j_username")))
username_input.send_keys(username)

# 显式等待密码输入框可交互
password_input = wait.until(EC.element_to_be_clickable((By.NAME, "j_password")))
password_input.send_keys(password)

print("something after scrape")

关键优化说明

  • 显式等待替代硬编码sleep:用WebDriverWait等待元素可交互,既保证元素加载完成再操作,又不会浪费多余时间,最多等待10秒(可根据实际情况调整)。
  • 使用标准定位语法:统一用By.NAME配合find_element,符合Selenium 4+的规范,避免语法错误。
  • 关闭冗余日志:通过ChromeOptions配置关闭浏览器日志,消除终端的DevTools和TensorFlow提示,让输出更干净。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:42:40