Home >Backend Development >Python Tutorial >How Can I Download HTTP Files (Like MP3s) in Python?

How Can I Download HTTP Files (Like MP3s) in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 21:29:20355browse

How Can I Download HTTP Files (Like MP3s) in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn