Search code examples
pythonhtmlpython-webbrowserbrowser-tab

Python - Displaying a web site in the same browser tab each time webbrowser.open is called


In Python, I would like to initially open a new browser tab and display a web site. The program will be displaying other png images before cycling back to displaying the web site again. It's like a slide show. I tried to use the webbrowser.open statement displayed below to open the web site with the "New" parameter equaling 1 expecting a new tab not to be opened, but every time webbrowser.open is called, a new tab opens on the Chrome browser.

Can you tell me what coding is needed to ensure once a tab is opened in the browser, additional calls to webbrowser.open won't open new tabs for the web site?

webbrowser.open('https://mawaqit.net/en/abricc-acton-01720-united-states', new=1)

Solution

  • I'm unfamiliar with the webbrowser tool, but using selenium webdriver the following all stays in the same tab.

    # import
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    # browser setup
    browser = webdriver.Chrome()
    browser.implicitly_wait(10)
    
    # open url
    browser.get("http://www.google.com")
    
    # click element on page (same tab)
    browser.find_element(By.XPATH,"/html/body/div[1]/div[1]/div/div/div/div[1]/div/div[2]/a").click()
    
    # open new URL (same tab)
    browser.get("http://www.stackoverflow.com")
    

    Also, some other tools available in selenium are below. These are useful if you want new tabs but need to switch back and forth to "parent" tabs:

    # assign tab variables (window_handle = tab apparently)
    window = browser.current_window_handle
    parent = browser.window_handles[0]
    child = browser.window_handles[1]
    
    # switch to new tab
    browser.switch_to.window(parent)
    

    I hope that at least some element of this is helpful.