【问题标题】:Changing focus to a new window in Python/Selenium在 Python/Selenium 中将焦点更改为新窗口
【发布时间】:2021-12-25 03:38:22
【问题描述】:

正如标题所说,我无法使用“driver.switch_to_window”让我的代码专注于新窗口。

我的任务是: 单击父页面上的按钮 > 出现新窗口 > 单击新窗口上的“接受”按钮并继续执行其余代码

driver.get("https:testpage.com/")
driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[2]/ul/li[1]/button").click()

#here the window appears
time.sleep(2)

driver.switch_to_window("windowName")
driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[3]/button[2]").click() #here nothing happens 



【问题讨论】:

  • 您需要窗口句柄。基本上你想先得到当前的窗口句柄。 (driver.getWindowHandle())... 新窗口打开后,获取所有窗口句柄 (driver.getWindowHandles()) 并遍历它们以找到不是原始句柄的那个。 (因为无法保证索引顺序...)请参阅此线程:stackoverflow.com/questions/45476200/… 另外请记住,新窗口可能尚未完成加载...最好在查找元素时使用 webdriverwait。 (以及更多有针对性的 xpath)

标签: python python-3.x selenium automation


【解决方案1】:

您可以尝试获取页面源,以便确定驱动程序是否已切换:

html_source = browser.page_source

它可能已经切换,但您的元素未加载或在 iframe 中。如果您的元素存在,那么您可以尝试使用不同的相对 XPath,例如找到最近的 id 并从中找到你的元素:

//div[@id='someid']//button[text()='someText'] 

我不使用绝对 XPath,因为我认为它们太脆弱了。

参考:
Python Selenium accessing HTML source

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多