【问题标题】:switch between tabs and perform action on individual using Selenium使用 Selenium 在选项卡之间切换并对个人执行操作
【发布时间】:2017-03-20 09:08:32
【问题描述】:

我正在尝试提取 URL,将它们打开到新选项卡中,然后执行一些操作。我的代码是-

urls = self.driver.find_elements_by_xpath('//div[@id="maincontent"]/table/tbody/tr/td//a[@href]')
        for url in urls:

            try:
                href = url.get_attribute("href")[28:]
                print href
                actions = ActionChains(self.driver)
                url_1 = self.driver.find_element_by_xpath('//*[@href="'+href+'"]')
                actions.key_down(Keys.CONTROL).click(url_1).key_up(Keys.CONTROL).perform()
            except Exception, e:
                print e

        actions1 = ActionChains(self.driver)      
        actions1.key_down(Keys.CONTROL).key_down(Keys.TAB).key_up(Keys.TAB).key_up(Keys.CONTROL).perform()
        print "hi"
        show_report = self.driver.find_element_by_xpath('//*[@value="Show Report(s)"]')
        show_report.click()

它在新选项卡中打开 URL,但不对它们执行操作。我该怎么办??

【问题讨论】:

    标签: python selenium scrapy


    【解决方案1】:

    您需要将焦点转移到新标签上,因为它们通常会在后台打开。然后你需要为当前的标签获取一个句柄。

    这是here描述的:

    import selenium.webdriver as webdriver
    import selenium.webdriver.support.ui as ui
    from selenium.webdriver.common.keys import Keys
    from time import sleep    
    
    browser = webdriver.Firefox()
    browser.get('https://www.google.com?q=python#q=python')
    first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
    first_link = first_result.find_element_by_tag_name('a')
    
    # Save the window opener (current window, do not mistaken with tab... not the same)
    main_window = browser.current_window_handle
    
    # Open the link in a new tab by sending key strokes on the element
    # Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
    first_link.send_keys(Keys.CONTROL + Keys.RETURN)
    
    # Switch tab to the new tab, which we will assume is the next one on the right
    browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
    
    # Put focus on current window which will, in fact, put focus on the current visible tab
    browser.switch_to_window(main_window)
    
    # do whatever you have to do on this page, we will just got to sleep for now
    sleep(2)
    
    # Close current tab
    browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
    
    # Put focus on current window which will be the window opener
    browser.switch_to_window(main_window)
    

    【讨论】:

    • send_keys(Keys.CONTROL + 'w')、send_keys(Keys.CONTROL + 't') 等键不起作用
    • @V.Khakhil 您需要使用适合您的浏览器和操作系统的任何密钥。 ctrl+wctrl+t 应该适用于 Windows 中的三个主要浏览器。
    • 我正在使用 windows 7 和 chrome web 驱动程序,但这些键仍然不起作用
    • This answer 列出了一些其他切换标签的方法。
    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多