[英]How to switch between different chrome browser window opened by different WebDriver using selenium in Python?
[英]How to switch tabs using the expected conditions new_window_is_opened and verify the page title using Selenium and Python
我正在編寫一個測試,它會遍歷多個頁面,然后驗證標題是否正在顯示。 目前我的測試是在我可以點擊一個按鈕並打開一個報告的地方。 問題是報告在新選項卡中打開,所以我需要我的測試來移動選項卡並驗證新選項卡中的標題。
需要驗證的標題是“估值”。 我做了一個斷言來確認標題和我預期的一樣
我在 python 中編寫了以下代碼。 它目前在第二行等待失敗
current = self.driver.current_window_handle
wait(self.driver, 10).until(EC.new_window_is_opened(self.driver.window_handles))
self.driver.switch_to.window([w for w in self.driver.window_handles if w != current][0])
title = self.driver.title
self.assertTrue("Valuation" == self.driver.title)
我正在使用以下代碼行打開一個新選項卡:
element = driver.find_element_by_xpath("//input[@id='save' and @name='save'][@value='View Report']")
driver.execute_script("arguments[0].click();", element)
new_window_is_opened(current_handles)
是期望打開一個新的 window 並增加 windows 句柄的數量。
The following example opens the url http://www.google.co.in first and then opens the url https://www.yahoo.com in the adjacent tab:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("http://www.google.co.in")
windows_before = driver.window_handles
driver.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(driver, 20).until(EC.new_window_is_opened(windows_before))
driver.switch_to.window([x for x in driver.window_handles if x not in windows_before][0])
注意:傳遞給
new_window_is_opened(current_handles)
的參數是一個列表。 為了創建一個列表,我們需要使用windows_before = driver.window_handles
在您的代碼塊中,預計當您:
current = self.driver.current_window_handle
僅存在一個 window 手柄。 所以繼續前進,代碼行:
wait(self.driver, 10).until(EC.new_window_is_opened(self.driver.window_handles))
將等待打開新的 window 並增加 windows 句柄的數量,並且僅在執行打開新 window 的操作后才會發生,這似乎從您的代碼塊中丟失。
插入啟動新窗口句柄打開的代碼行:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
windows_before = driver.window_handles
element = driver.find_element_by_xpath("//input[@id='save' and @name='save'][@value='View Report']")
driver.execute_script("arguments[0].click();", element)
WebDriverWait(self.driver, 10).until(EC.new_window_is_opened(windows_before))
driver.switch_to.window([x for x in driver.window_handles if x not in windows_before][0])
assertTrue("Valuation" == driver.title)
注意:根據您在評論中更新的代碼行,您沒有使用Python class ,因此您不應使用關鍵字
self
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.