In Playwright for Python, to save the full HTML of a locator, including all child elements, you can use the inner_html method of a locator instance. This method will return the inner HTML content as a string, which you can then write to a file or manipulate as needed.
Here's a step-by-step guide on how to do this:
- Install Playwright: Make sure you've installed Playwright and the necessary browser binaries. If you haven't installed it yet, you can do it using pip:
pip install playwright
playwright install
- Write the code: Create a Python script to navigate to the desired page, locate the element, and retrieve the inner HTML.
Here's an example script that saves the entire HTML of the page body (<body> tag):
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
# Launch the browser
browser = await p.chromium.launch()
page = await browser.new_page()
# Navigate to the desired URL
await page.goto('https://example.com')
# Get the locator for the element you're interested in
# Here I'm using 'body', but you can use any selector for the element you need
locator = page.locator('body')
# Retrieve the inner HTML of the element
inner_html = await locator.inner_html()
# Now you can save the inner HTML to a file
with open('page_content.html', 'w', encoding='utf-8') as f:
f.write(inner_html)
# Close the browser
await browser.close()
asyncio.run(main())
Make sure to adjust 'https://example.com' to the URL of the webpage you're interested in and page.locator('body') to target the specific element whose HTML you want to capture.
- Run the script: Save your script to a file (e.g.,
save_html.py) and execute it with Python:
python save_html.py
This will create a file named page_content.html in the same directory as your script, containing the inner HTML of the selected locator (which is <body> in this example).
Please note that the example above uses async_playwright which is the asynchronous version of Playwright. If you prefer to use the synchronous API, you replace async_playwright with sync_playwright, remove the async and await keywords, and do not use asyncio.run(main()) to execute the main function. Here is how you can adapt the code to synchronous API:
from playwright.sync_api import sync_playwright
def main():
with sync_playwright() as p:
# Launch the browser
browser = p.chromium.launch()
page = browser.new_page()
# Navigate to the desired URL
page.goto('https://example.com')
# Get the locator for the element you're interested in
locator = page.locator('body')
# Retrieve the inner HTML of the element
inner_html = locator.inner_html()
# Now you can save the inner HTML to a file
with open('page_content.html', 'w', encoding='utf-8') as f:
f.write(inner_html)
# Close the browser
browser.close()
main()