Downloading HTTP Files with Python
Enhancing your utility to download MP3 files directly within Python can streamline your workflow.
Solution using Python's Built-In Module:
Python provides the urllib.request module for handling HTTP requests. To download a file using this module:
import urllib.request url = "http://www.example.com/songs/mp3.mp3" filename = "mp3.mp3" urllib.request.urlretrieve(url, filename)
This code initiates an HTTP GET request to the specified URL. If the response contains a file, Python downloads it and saves it to the specified filename.
Solution using the requests Library:
An alternative approach is to use the third-party requests library, which offers additional features and flexibility.
import requests url = "http://www.example.com/songs/mp3.mp3" filename = "mp3.mp3" response = requests.get(url) with open(filename, "wb") as f: f.write(response.content)
In this case, the requests.get() method retrieves the HTTP response and assigns it to the response variable. Then, the response content is written to the filename using a file-like object created with open.
The above is the detailed content of How Can I Download HTTP Files (Like MP3s) in Python?. For more information, please follow other related articles on the PHP Chinese website!