首页 > 解决方案 > Selenium 无法打开新窗口/选项卡

问题描述

我目前正在尝试使用 selenium 抓取网站。我有一个包含元素的表格,我想单击每个元素,在新窗口/选项卡中打开链接,处理此窗口/选项卡,关闭它并单击下一个元素等。到目前为止,我可以单击表,打开链接并处理页面。不幸的是,我无法在新窗口或标签中打开链接。

我无法向元素发送键盘命令。我也试过

action = ActionChains(self.driver)
    action.move_to_element(ele)\
    .key_down(Keys.SHIFT)\
    .click(ele)\
    .key_up(Keys.SHIFT)\
    .perform()

这以某种方式仅在当前窗口中打开链接(我没有得到新的窗口句柄,仍然只有一个)。如果有任何帮助,我将不胜感激。

编辑:我也无法使用浏览器手动打开新窗口/标签中的链接。

标签: pythonseleniumweb-crawler

解决方案


要访问 URL,例如https://www.google.co.in然后单击一个元素,例如作为Gmail的文本链接以在新窗口/标签中打开链接,您可以按照以下解决方案使用类:action_chains

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains
    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:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('https://www.google.co.in')
    print("Page Title is : %s" %driver.title)
    mail_link = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Gmail")))
    ActionChains(driver).key_down(Keys.CONTROL).click(mail_link).key_up(Keys.CONTROL).perform() 
    
  • 浏览器快照:

Google_Gmail


推荐阅读