Write simple Python script to get webpage via HTTPS request and save it as PDF file.…
- User
Write simple Python script to get webpage via HTTPS request and save it as PDF file. Don't forget useragent
- Assistant
To fetch a webpage via an HTTPS request and save it as a PDF file in Python, you can use libraries such as
requeststo handle the HTTP request andpdfkitto convert the HTML content to a PDF. Below is a simple script that demonstrates this process.Before running this script, make sure you have the required libraries installed. You can install them using
pip: - User
Rewrite without wkhtmltopdf
- Assistant
If you prefer to avoid using
wkhtmltopdf, you can use theweasyprintlibrary, which does not require any external binaries. WeasyPrint is an excellent tool for converting HTML pages to PDF and is much easier to manage as it is a pure Python implementation.To use
weasyprint, you need to install it first:pip install requests weasyprintHere's how you can modify the script to use
weasyprint:import requests from weasyprint import HTML def fetch_webpage_to_pdf(url, output_pdf): # Set a user agent to mimic a browser request headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } try: # Fetch the webpage response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for HTTP errors # Convert HTML content to a PDF HTML(string=response.text).write_pdf(output_pdf) print(f"Webpage saved as PDF: {output_pdf}") except requests.RequestException as e: print(f"An error occurred while fetching the webpage: {e}") except Exception as e: print(f"An error occurred while converting to PDF: {e}") # Example usage url = 'https://example.com' output_pdf = 'webpage.pdf' fetch_webpage_to_pdf(url, output_pdf)