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

Selenium登录后校验新URL失败 如何正确获取驱动更新后的页面链接

问题原因

  • driver.get()方法仅负责导航到指定URL,没有返回值,你将该方法的执行结果赋值给new_link,得到的永远是None,和目标URL字符串比较自然永远返回False,输出No。
  • current_url是WebDriver实例的属性,不是可调用方法,不需要加括号执行,driver.current_url()的写法会直接抛出错误,且直接打印driver对象只会输出对象内存地址,无法得到页面URL。
  • 隐式等待仅作用于元素查找的超时逻辑,不会等待页面跳转完成,登录点击后可能页面还未完成跳转就执行了URL获取逻辑,拿到的仍是旧页面地址。

修复后的代码示例

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

PATH = '/Applications/chromedriver'
driver = webdriver.Chrome(PATH)
driver.get('https://url')
# 隐式等待全局设置一次即可,不需要重复声明
driver.implicitly_wait(5)

def login_function():
    # 旧版find_element_by_*语法已弃用,建议统一使用By定位
    name_element = driver.find_element(By.NAME, 'email')
    name_element.send_keys('admin@xyz.com')
    password_element = driver.find_element(By.NAME, 'password')
    password_element.send_keys('pass')
    login_button = driver.find_element(By.CLASS_NAME, 'custom-btn-wrapper')
    login_button.click()
    
    # 显式等待登录后URL跳转完成,最多等10秒
    WebDriverWait(driver, 10).until(EC.url_changes(driver.current_url))
    # 直接拿属性赋值,不需要加括号
    current_new_url = driver.current_url
    
    # 如果需要主动导航到新页面再拿URL,按以下写法
    # driver.get('https://new_url')
    # 等待新页面加载完成
    # WebDriverWait(driver, 10).until(EC.url_to_be('https://new_url'))
    # current_new_url = driver.current_url
    
    if current_new_url == 'https://new_url':
        print('Yes')
    else:
        print('No')
    # 返回URL供后续逻辑使用
    return current_new_url

# 调用函数拿到跳转后的URL
final_url = login_function()
print(final_url)

补充说明

如果登录后是系统自动跳转,不需要主动调用driver.get()导航到新地址,等待跳转完成后直接取current_url即可。如果确实需要主动访问新地址,导航完成后同样取current_url属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:00