Selenium Python不会关闭子窗口 [英] Selenium Python does not close the child window
问题描述
我有一个网页,单击该网页可打开新的浏览器窗口.我可以得到2个句柄,但是driver.close()总是关闭第一个/主窗口.
I have webpage which open new browser window on click. I am able to get 2 handles however driver.close() always closes the first/main window.
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("file:///D:/blackhole/print.html")
han = driver.window_handles
print("handles:", han) # gets 1 handle
time.sleep(2)
click_btn = driver.find_element_by_link_text('Print')
click_btn.click()
han = driver.window_handles
print("handles:", han) # gets 2 handles
driver.switch_to_window = han[1] # first element is always first window handle
driver.close() # main window close
在调用新窗口的网页代码下方
Below webpage code which invokes new window
<a href="print.html"
onclick="window.open('popprint.html',
'newwindow',
'width=300,height=250');
return false;"
>Print</a>
与Firefox行为相同. Python 3.6.7
Same behaviour for Firefox as well. Python 3.6.7
推荐答案
硒无法关闭活动窗口,即新打开的窗口 >,因为实际上您没有干净地切换到新打开的窗口.
Selenium is unable to close the active window i.e the newly opened window because practically you havn't switched to the newly opened window in a clean way.
关于标签页/窗口切换/处理的几句话:
A few words about Tab/Window switching/handling:
-
switch_to_window(window_name)
已被弃用一段时间,您需要使用 WebDriverWait 与 Tabs/Windows 之前,先在support.expected_conditions.html#selenium.webdriver.support.expected_conditions.number_of_windows_to_be"rel =" nofollow noreferrer>number_of_windows_to_be(num_windows)
上. - 始终跟踪子窗口句柄,以便您可以在需要时遍历.
- 始终将 WebDriverWait 与
expected_conditions
一起用作 ,然后提取页面标题. -
这是您自己的代码,上面有一些小的调整:
switch_to_window(window_name)
is deprecated for quite some time now and you need to usedriver.switch_to.window
- Always keep track of the Parent Window handle so you can traverse back later if required as per your usecase.
- Always use WebDriverWait with expected_conditions as
number_of_windows_to_be(num_windows)
before switching between Tabs/Windows. - Always keep track of the Child Window handles so you can traverse whenever required.
- Always use WebDriverWait with
expected_conditions
astitle_contains("partial_page_title")
before extracting the Page Title. Here is your own code with some minor tweaks mentioned above:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox(executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get("file:///D:/blackhole/print.html")
parent_han = driver.window_handles
driver.find_element_by_link_text('Print').click()
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
all_han = driver.window_handles
new_han = [x for x in all_han if x != parent_han][0]
driver.switch_to.window(new_han)
driver.close()
您可以在硒开关标签中找到详细的讨论
You can find a detailed discussion in Selenium Switch Tabs
这篇关于Selenium Python不会关闭子窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!