Python和selenium,是不是可以打开带有URL的新选项卡?

时间:2016-02-15 08:32:01

标签: python selenium

我一直在挖这个但没有运气。所以我的问题是:无法在新标签中打开新网址? (在这种情况下使用IE)。 我的方案是,打开IE,打开网站,登录,执行一些任务,然后在该选项卡中打开一个带有新URL的新选项卡。当我这样做时,新网址始终在第一个标签中打开,而不是在新标签中打开。我在网上找了一些解决方案,但任何工作都找到了很多人也有同样的问题。代码如下:

        from selenium import webdriver
        from selenium.webdriver.common.keys import Keys

        path_to_Ie = 'C:\\Python34\\IEDriver\\IEDriverServer.exe' # change path as needed
        browser = webdriver.Ie(executable_path = path_to_Ie)
        url = 'www.test1.com'
        browser.get(url)


        browser.find_element_by_xpath("//*[@id='username']").send_keys("user")
        browser.find_element_by_xpath("//*[@id='password']").send_keys("pass")

        browser.find_element_by_xpath("//*[@id='login-link']").click()

    # some coding here


        browser.find_element_by_tag_name("body").send_keys(Keys.CONTROL + 't') #open new tab

        browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) # it looks like it switches to the correct tab, but anyway the browser.get will open the url in the first tab

        browser.get('www.test2.com') # this link must open in this new tab -> but it doesnt.


        import os
        os.system("taskkill /im IEDriverServer.exe")
谢谢你!

1 个答案:

答案 0 :(得分:0)

browser.execute_script("window.open('www.test2.com','_blank');")

这适用于Chrome,但在IE中,它会打开新窗口而不是新标签。如果它对您没有关系,那么您可以尝试一下