write a python script that scrape the rendered part of html webpage from a list of…
- User
write a python script that scrape the rendered part of html webpage from a list of links. output as txt within folder
- Assistant
write a python script that scrape the rendered part of html webpage from a list of links. output as txt within folder
Certainly! Below is a Python script that will scrape the rendered HTML content from a list of web page URLs and save each page's content as a .txt file within a folder. This script uses Playwright, a powerful library for automating browsers, which allows it to execute JavaScript and fetch the fully rendered HTML of web pages.
Important Note: When scraping web content, please ensure that you comply with all applicable laws and the terms of service of the websites you are accessing. This script is intended for educational purposes and should be used responsibly.
scraper.pyimport os
import asyncio
from playwright.async_api import async_playwright
async def scrape_pages(urls, output_dir):
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
async with async_playwright() as p:
# Launch a headless browser instance
browser = await p.chromium.launch()
context = await browser.new_context()
page = await context.new_page()
for url in urls:
try:
print(f"Scraping {url}...")
# Navigate to the page
await page.goto(url, wait_until='load')
# Optionally, wait for additional content to load
await page.wait_for_load_state('networkidle')
# Get the rendered HTML content
content = await page.content()
# Create a safe filename based on the URL
filename = url.replace('https://', '').replace('http://', '').replace('/', '_').replace(':', '_')
file_path = os.path.join(output_dir, f"{filename}.txt")
# Save the content to a text file
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Saved content to {file_path}")
except Exception as e:
print(f"An error occurred while scraping {url}: {e}")
await browser.close()
def main():
# Read the list of URLs from a text file
with open('links.txt', 'r') as f:
urls = [line.strip() for line in f if line.strip()]
# Define the output directory
output_dir = 'output'
# Run the scraping task
asyncio.run(scrape_pages(urls, output_dir))
if __name__ == '__main__':
main()
Install Dependencies
First, you need to install the playwright package and set it up:
pip install playwright
playwright install
The playwright install command installs the browser binaries needed for Playwright to run.
Prepare Your List of URLs
Create a file named links.txt in the same directory as scraper.py. List all the URLs you want to scrape, one per line:
https://example.com/page1
https://example.com/page2
https://anotherdomain.com/some-page
Run the Script
Run the script using Python:
python scraper.py
The script will:
links.txt..txt file in the output directory.View the Results
After the script finishes running, you will find a directory named output containing the .txt files with the rendered HTML content of each page.
Handling JavaScript-Rendered Content
The use of Playwright allows the script to execute JavaScript and wait for all dynamic content to load, which is essential for pages that render content via JavaScript.
Customizing Wait Conditions
Depending on the complexity of the pages you're scraping, you might need to adjust the wait conditions. For example, you could wait for specific elements to appear:
await page.wait_for_selector('#content')
Error Handling
The script includes basic error handling to continue processing other URLs even if one fails.
Respecting Website Policies
Always make sure to:
Extending the Script
You can modify the script to:
.txt, such as .html or JSON files.This script is provided for educational purposes. Web scraping may be subject to legal restrictions and website terms of service. Ensure you have the right to scrape the sites you target and that you comply with all relevant laws and regulations.