How to open a new window on a browser using Selenium WebDriver for python?

后端 未结 4 888
谎友^
谎友^ 2020-12-05 19:10

I am attempting to open a new tab OR a new window in a browser using selenium for python. It is of little importance if a new tab or new window is opened, it is only import

相关标签:
4条回答
  • 2020-12-05 19:47

    I recommend to use CTRL + N command on Firefox to reduce less memory usage than to create new browser instances.

    import selenium.webdriver as webdriver
    from selenium.webdriver.common.keys import Keys
    
    browser = webdriver.Firefox()
    body = browser.find_element_by_tag_name('body')
    body.send_keys(Keys.CONTROL + 'n')
    

    The way to switch and control windows has already been mentioned by Dhiraj.

    0 讨论(0)
  • 2020-12-05 19:58

    How about you do something like this

    driver = webdriver.Firefox() #First FF window
    second_driver = webdriver.Firefox() #The new window you wanted to open
    

    Depending on which window you want to interact with, you send commands accordingly

    print driver.title #to interact with the first driver
    print second_driver.title #to interact with the second driver
    

    For all down voters:


    The OP asked for "it is only important that a second instance of the browser is opened.". This answer does not encompass ALL possible requirements of each and everyone's use cases. The other answers below may suit your particular need.

    0 讨论(0)
  • 2020-12-05 20:03

    You can use execute_script to open new window.

    driver = webdriver.Firefox()
    driver.get("https://linkedin.com")
    # open new tab
    driver.execute_script("window.open('https://twitter.com')")
    print driver.current_window_handle
    
    # Switch to new window
    driver.switch_to.window(driver.window_handles[-1])
    print " Twitter window should go to facebook "
    print "New window ", driver.title
    driver.get("http://facebook.com")
    print "New window ", driver.title
    
    # Switch to old window
    driver.switch_to.window(driver.window_handles[0])
    print " Linkedin should go to gmail "
    print "Old window ", driver.title
    driver.get("http://gmail.com")
    print "Old window ", driver.title
    
    # Again new window
    driver.switch_to.window(driver.window_handles[1])
    print " Facebook window should go to Google "
    print "New window ", driver.title
    driver.get("http://google.com")
    print "New window ", driver.title
    
    0 讨论(0)
  • 2020-12-05 20:04
    driver = webdriver.Chrome()
    driver.execute_script("window.open('');")
    driver.get('first url')
    
    driver.switch_to.window(driver.window_handles[1])
    driver.get('second url')
    
    0 讨论(0)
提交回复
热议问题