简体   繁体   English

Selenium Python:切换窗口并查找元素

[英]Selenium Python: Switch window and find element

I am downloading an excel report from a URL.我正在从 URL 下载 Excel 报告。 When I click excel download, a new window pops up with a 'in progress' message initially and followed by a 'completion' message.当我单击 excel 下载时,会弹出一个新窗口,最初显示“进行中”消息,然后是“完成”消息。 I want to close Chrome session after completing the download.我想在完成下载后关闭 Chrome 会话。 I am using below code but somehow I am unable to locate element on new window.我正在使用下面的代码,但不知何故我无法在新窗口上找到元素。 Kindly advise where am I wrong.请告知我哪里错了。 (PS: I can't share URL) (PS:我不能分享网址)

    #Excel Download
    link = driver.find_elements_by_xpath("//img[@alt='Export to Excel']")[0]
    link.click()
    driver.switch_to_window
    time.sleep (5)
    element = WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID,"_NS__workingMsg")))
    element = WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH,"//*[text()='Your report is ready and will download to your Web browser in a few moments.']")))
    time.sleep (2)
    driver.close()

In that case you would need to switch the driver focus to new window :在这种情况下,您需要将驱动程序焦点切换到新窗口:

current_handle = driver.window_handles
link = driver.find_elements_by_xpath("//img[@alt='Export to Excel']")[0]
link.click()
new_handle = driver.window_handles
driver.switch_to.window(new_handle[1])

and then you can perform action on new window.然后您可以在新窗口上执行操作。

Update 1 :更新 1:

to close both of them you can do this :要关闭它们,您可以这样做:

driver.close()

driver.switch_to.window(new_handle[0])

driver.close()

or otherwisem, directly do this :否则,直接这样做:

driver.quit()

quite will close all instance相当将关闭所有实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM