Close or Switch Tabs in Playwright/Python

Question:

I’m doing an automation, at the time of download it opens a tab, sometimes it doesn’t close automatically, so how can I close a tab in playwright using python?

Asked By: user19016544

||

Answers:

I managed to make a code that closes only a specific tab!

all_pages = page.context.pages
await all_pages[1].close()
Answered By: user19016544

You can also use the close method on the Page object that represents the tab you want to close. Here is an example of how you might do this:

# launch a browser and create a new context
browser = await playwright[browserType].launch()
context = await browser.newContext()

# create a new page and go to the URL you want to download from
page = await context.newPage()
await page.goto("https://www.example.com")

# download a file from the page
await page.click("#download-button")

# wait for the download to finish and the new tab to be created
await page.waitForSelector("#download-complete")

# get a list of pages in the current context
pages = await context.pages()

# assume the last page in the list is the new tab that was created
# (you may need to adapt this to your specific use case)
newTab = pages[-1]

# close the new tab
await newTab.close()
Answered By: Niwrad