python不关闭窗口_Selenium Python不会关闭子窗口

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

οnclick="window.open('popprint.html',

'newwindow',

'width=300,height=250');

return false;"

>Print

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.

Solution

A few words about Tab/Window switching/handling:

switch_to_window(window_name) is deprecated for quite some time now and you need to use driver.switch_to.window

Always keep track of the Parent Window handle so you can traverse back later if required as per your usecase.

Always keep track of the Child Window handles so you can traverse whenever required.

Always use WebDriverWait with expected_conditions as title_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值