简体   繁体   中英

*** Solved *** 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)

the docs says

webbrowser.open(url, new=0, autoraise=True) Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised if possible (note that under many window managers this will occur regardless of the setting of this variable).

Nothing here says that it can replace or close the current tab, so I am afraid that you will have to use something like Selenium instead.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM