Selenium Python:execute_script在循环中只执行一次



我想在不关闭浏览器的情况下执行以下任务 3 次。 在选项卡中打开 Google.com。 打开新标签页 然后关闭包含 Google.com 的选项卡 在上一个新打开的选项卡中打开 Google.com。

我使用以下代码打开新选项卡:

browser.execute_script("window.open('', 'new_tab')")

但是当在循环中执行时,它只执行一次。

我已经打印了窗口句柄的数量,这表明execute_script只执行一次。

我的完整代码:

cpath="C:/Users/Gupta Niwas/Downloads/Softwares/Browsers/Drivers/chromedriver_win32/chromedriver.exe"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
chrome_options.add_argument("start-maximized")
#browser = webdriver.Firefox(executable_path=fpath)
browser = webdriver.Chrome(chrome_options=chrome_options,executable_path=cpath)

for i in range(3):
browser.get("https://google.com")
print(len(browser.window_handles))
print("current:",browser.current_window_handle)
browser.execute_script("window.open('', 'new_tab')")
print(len(browser.window_handles))
next_tab=browser.window_handles[len(browser.window_handles)-1]
print(next_tab)
print(browser.title)
browser.close()
print(len(browser.window_handles))
browser.switch_to_window(next_tab)
browser.delete_all_cookies()

在第二个循环中,它抛出一个异常:

runfile('C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py', 
wdir='C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi')
1
current: CDwindow-75E62D95A2A8A7808C5AC369A8070641
2
CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
Google
1
1
current: CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
1
CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
Google
Traceback (most recent call last):
File "<ipython-input-1-12046950abfa>", line 1, in <module>
runfile('C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py', wdir='C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi')
File "C:ProgramDataAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:ProgramDataAnaconda3libsite-packagesspyderutilssitesitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py", line 34, in <module>
print(len(browser.window_handles))
File "C:ProgramDataAnaconda3libsite-packagesseleniumwebdriverremotewebdriver.py", line 719, in window_handles
return self.execute(Command.GET_WINDOW_HANDLES)['value']
File "C:ProgramDataAnaconda3libsite-packagesseleniumwebdriverremotewebdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:ProgramDataAnaconda3libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: no such session
(Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)

我认为这是一个问题:

next_tab = browser.window_handles[len(browser.window_handles)-1]

您的next_tab正在获取当前窗口引用。当您关闭当前窗口时:

browser.close()

您无法切换到next_tab,因为它不存在。我建议你调试你的代码,找出你应该在browser.window_handles[?]中具有哪个值

相关内容

  • 没有找到相关文章

最新更新