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

Selenium Python如何在当前激活的浏览器标签页中打开新URL

Python Selenium 当前标签页跳转URL解决方案

driver.get() 方法默认行为就是在当前激活标签页加载目标URL,不会主动触发新窗口打开。出现新开窗口的情况通常是目标站点的自动弹窗逻辑、反爬机制导致的。

你提到的Java版本driver.navigate.to()在Python Selenium中同样可用,效果和driver.get()完全等价,写法如下:

driver.navigate.to("目标URL")

如果上述方法仍然出现新开窗口的问题,可以用执行原生JavaScript的方式强制在当前页跳转,完全避开站点的弹窗触发逻辑:

driver.execute_script("window.location.href = '目标URL'")

修改后完整代码示例

import socket
import httplib
from selenium.webdriver.remote.command import Command

def get_status(driver):
    try:
        driver.execute(Command.STATUS)
        return "Alive"
    except (socket.error, httplib.CannotSendRequest):
        return "Dead"

# 先确认切换到当前激活标签页,避免操作错窗口
driver.switch_to.window(driver.window_handles[-1])

if get_status(driver) == 'Alive':
    # 用JS强制跳转,不会开新窗口
    driver.execute_script("window.location.href = 'https://www.amazon.in'")
else:
    driver.execute_script("window.location.href = 'https://www.google.in'")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:30:02