【发布时间】:2018-08-29 06:26:16
【问题描述】:
我正在尝试编写一个函数,该函数将接收“浏览器实例”(我的意思是webdriver.Firefox())并将打开一个带有特定 URL 的新标签。
这是函数:
def open_New_TAB(BrowserInstance, URL):
if URL_Validation(URL):
script = "window.open('" + URL + "')"
BrowserInstance.execute_script(script)
else:
print('Invalid URL')
return
URL_Validation 如果 URL 有效,则返回 True
BrowserInstance是以下函数的返回,它只在get(URL)完成后返回某个浏览器类型的“浏览器实例”:
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 函数打开的同一浏览器窗口中打开一个新标签:
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 也没有异常)
【问题讨论】:
-
我猜测无法为“浏览器”实例打开新标签的原因是因为我没有使用默认配置文件。但是,我仍然不知道如何解决这个问题
标签: python python-3.x selenium selenium-webdriver selenium-firefoxdriver