如何通过selenium webdriver和python切换到另一个TAB?

时间:2018-06-13 14:25:49

标签: python-3.x selenium selenium-webdriver tabs webdriver

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import autoit
wait = WebDriverWait
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'C:\\chromedriver\\chromedriver.exe')
driver.maximize_window()
driver.get("https://www.arttoframe.com/search")
action = ActionChains(driver)
link = driver.find_element_by_xpath('//*[@id="apply_frame_main_0"]')
action.key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform()
time.sleep(2)

C:\ Users \ Dell \ PycharmProjects \ untitled \ venv \ Scripts \ python.exe C:\ Users \ Dell \ PycharmProjects \ untitled3 \ ATF_TestOrder.py

处理完成,退出代码为0

1 个答案:

答案 0 :(得分:0)

要在相邻的选项卡中打开 Pictute Frame 并切换到它,您可以使用 ActionChains ,如下所示:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("https://www.arttoframe.com/search")
    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='apply_frame_main_0']")))
    windows_before  = driver.current_window_handle
    ActionChains(driver).key_down(Keys.CONTROL).click(element).key_up(Keys.CONTROL).perform()
    WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to_window(new_window)
    print(driver.title)
    
  • 控制台输出:

    8x10 Satin Black picture frame
    
  • 浏览器快照:

switch_to_new_tab