我正在尝试编写一个函数,它将接收"browser instance"(并且我的意思是 webdriver.Firefox()
)并将打开一个带有特定URL的新选项卡 .
This is the function:
def open_New_TAB(BrowserInstance, URL):
if URL_Validation(URL):
script = "window.open('" + URL + "')"
BrowserInstance.execute_script(script)
else:
print('Invalid URL')
return
如果URL有效, URL_Validation
将返回True
BrowserInstance
是以下函数的返回值,该函数仅在 get(URL)
完成后返回某个浏览器类型的"browser instance":
def Open_Browser (URL=None, browserType='FF', Browser_Wait=20, Hide=False,
Maximize=False, Retries=3):
if browserType == 'FF' or browserType == 'FireFox' or browserType == 'Firefox' or browserType == 'firefox':
# FireFox Parameters
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = False
browser = webdriver.Firefox(firefox_profile = profile, executable_path='G:\\Python\\geckodriver-v0.19.1-win64\\geckodriver.exe')
elif browserType == 'Chrome' or browserType == 'chrome':
# Chrome Parameters
browser = webdriver.Chrome(executable_path="G:\\Python\\chromedriver_win32\\chromedriver.exe")
elif browserType == 'IE' or browserType == 'Ie' or browserType == 'Explorer':
browser = webdriver.Ie(executable_path="G:\\Python\\IEDriverServer_x64_3.8.0\\IEDriverServer.exe")
else:
print('No such browser type')
browser.implicitly_wait(Browser_Wait) # Implicit wait
browser.set_page_load_timeout(20) # Set the Timeout for waiting till the page loads
for attempt in range(Retries):
try:
browser.get(URL)
except TimeoutException:
print("Timeout Expired at the:", attempt+1,'attempt')
# browser.close()
continue
return browser
我期待 open_New_TAB
将在运行以下脚本后由 Open_Browser
函数打开的同一浏览器窗口中打开一个新的TAB:
browser = Open_Browser('http://10.0.1.76')
open_New_TAB(browser, 'http://10.0.7.131')
但是,不幸的是,结果是为 'http://10.0.7.131'
打开了一个新的浏览器窗口 .
我不明白为什么我有一个新窗口而不是新的TAB,因为当我使用以下脚本时,我确实得到了新的TAB . 这个脚本完全相同但没有这个功能
driver = webdriver.Firefox()
driver.get("https://10.0.1.76")
driver.execute_script("window.open('https://10.0.1.76')")
如果有人告诉我我做错了什么,我会非常感激 . 如果您有另一种方法来完成打开新TAB的任务,那就没关系 . 顺便说一句,我试图使用: driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
但没有成功(我没有得到新的TAB也没有例外)
2 回答
You are getting a new window because you are asking for a new window
您正在使用的JavaScript在命令中说明了它 . Firefox中有一个设置可以在选项卡中打开新窗口,但我不确定它是否适用于Selenium测试 .
它被称为
browser.link.open_newwindow
. 值为2,值为3 . 您可以尝试通过配置文件设置值,看看会发生什么 .正如MivaScott所说
这是正确的,但据我所知,由于它是一个冻结值,因此无法更改此值 . 我以前试过这个,这就是我的结论 . 我切换到chrome来解决这个问题,但是当然如果你一定要使用firefox我恐怕你需要做一些像下载firefox驱动程序源代码的东西,手动将这个硬编码值设置为正确的值(2,I假设)并从该编辑的源构建webdriver .