save the raw html of a url string to a local file in python

You can use the urllib library to fetch the html content of the url string and write it to a local file using file handling. Here's an example code snippet:

main.py
import urllib.request

url = "https://www.example.com"
filename = "example.html"

with urllib.request.urlopen(url) as response:
   html = response.read()

with open(filename, "wb") as f:
   f.write(html)
204 chars
11 lines

Explanation:

  • We import the urllib.request module to fetch the url data.
  • We specify the url and filename where we want to save the data.
  • We open the url using urllib.request.urlopen() and get the html content using response.read().
  • We open the file using open() method in write mode and write the fetched html content to it using f.write() method. We use "wb" mode for writing binary data to the file.

gistlibby LogSnag