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

Selenium切换窗口后仍无法定位Medium登录页已存在的邮箱输入框

问题原因及解决方案

1. 错误切换窗口上下文

medium的邮箱登录表单是当前页面内的模态弹窗,不会触发新窗口创建,你无需切换window handle。切换到不存在/无关的第二个窗口,会导致driver指向错误的页面上下文,这就是你打印page_source和断点实时观测内容不一致的核心原因。你可以点击邮箱登录后打印len(driver.window_handles)验证,正常情况下窗口数量始终为1。

2. CLASS_NAME定位语法错误

Selenium的By.CLASS_NAME仅支持传入单个类名,你传入的eo al是两个独立的类名,所以永远无法匹配到对应元素。如果需要同时匹配多个类,应该改用By.CSS_SELECTOR,写法为.eo.al。

3. 其他定位方法语法错误

你注释的XPath写法错误,aria-label是元素属性而非标签,正确的邮箱输入框XPath写法为//input[@aria-label="email"]。这种定位方式比依赖类名更稳定,因为medium的类名多为前端动态生成,随时可能变动,而aria-label是语义属性,不会轻易修改。


修正后可运行代码

import requests as re
from bs4 import BeautifulSoup
import pymongo
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
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

options = Options()
options.headless = False
driver = webdriver.Chrome(executable_path = "C:\\Users\Dominick\Desktop\chromedriver.exe", options = options)

driver.get('https://medium.com/m/signin')
# 等待邮箱登录按钮可点击后再操作
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "email-susi-button-text"))).click()

try:
    # 优先用aria-label定位,稳定性最高
    inputdiv = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//input[@aria-label="email"]')))
    print('Success')
    # 输入邮箱示例:inputdiv.send_keys("test@example.com")
except NoSuchElementException:
    print('Element not found')

额外提示

medium有较强的反机器人检测机制,原生Selenium大概率会被识别,后续如果出现收不到登录链接、请求被拦截的情况,可以改用undetected-chromedriver绕过基础检测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:45:04