search
HomeBackend DevelopmentPython Tutorial11 postures downloaded using Python, each more advanced than the last

使用 Python 下载的11种姿势,一种比一种高级

Below you will learn how to overcome various challenges you may encounter, such as downloading redirected files, downloading large files, completing a multi-threaded download, and other strategies.

1. Using requests

You can use the requests module to download files from a URL.

Consider the following code:

使用 Python 下载的11种姿势,一种比一种高级

You simply get the URL using the get method of the requests module and store the result into a variable called "myfile" middle. Then, write the contents of this variable to the file.

2. Using wget

使用 Python 下载的11种姿势,一种比一种高级

#You can also use Python’s wget module to download files from a URL. You can install the wget module using pip by following the command:

Consider the following code, which we will use to download the logo image for Python.

使用 Python 下载的11种姿势,一种比一种高级

In this code, the URL and path (where the image will be stored) are passed to the download method of the wget module.

3. Downloading Redirected Files

In this section, you will learn how to use requests to download a file from a URL that will be redirected to another with a .pdf The URL of the file. The URL looks like this:

使用 Python 下载的11种姿势,一种比一种高级

To download this pdf file, use the following code:

使用 Python 下载的11种姿势,一种比一种高级

In this paragraph In the code, the first step we specify is the URL. Then, we use the get method of the request module to get the URL. In the get method, we set allow_redirects to True, which will allow redirections in the URL and the redirected content will be assigned to the variable myfile. In addition, search the backend of the public account for top architects to reply "Interview Status" to get a surprise gift package.

Finally, we open a file to write the obtained content.

4. Download large files in chunks

Consider the following code:

使用 Python 下载的11种姿势,一种比一种高级

First, we use the get of the requests module as before method, but this time, we will set the stream property to True.

Next, we create a file named PythonBook.pdf in the current working directory and open it for writing.

Then, we specify the chunk size to be downloaded each time. We've set it to 1024 bytes, then iterated through each chunk and written those chunks to the file until the end of the chunk.

Isn't it beautiful? Don't worry, we will display a progress bar of the download process later.

5. Download multiple files (parallel/batch download)

To download multiple files at the same time, please import the following module:

使用 Python 下载的11种姿势,一种比一种高级

We imported the os and time modules to check how long it takes to download the file. The ThreadPool module allows you to run multiple threads or processes using a pool.

Let's create a simple function that sends the response in chunks to a file:

使用 Python 下载的11种姿势,一种比一种高级

This URL is a two-dimensional array that specifies your The path and URL of the page to download.

使用 Python 下载的11种姿势,一种比一种高级

Just like we did in the previous section, we pass this URL to requests.get. Finally, we open the file (the path specified in the URL) and write the page content.

Now, we can call this function for each URL individually, or we can call this function for all URLs at the same time. Let’s call this function for each URL individually in a for loop, paying attention to the timer:

使用 Python 下载的11种姿势,一种比一种高级

Now, replace the for loop with the following lines of code:

使用 Python 下载的11种姿势,一种比一种高级

Run the script.

6. Download using the progress bar

The progress bar is a UI component of the clint module. Enter the following command to install the clint module:

使用 Python 下载的11种姿势,一种比一种高级

Consider the following code:

使用 Python 下载的11种姿势,一种比一种高级

In this code, we first The requests module is imported, and then we import the progress component from clint.textui. The only difference is in the for loop. When writing content to a file, we use the bar method of the progress bar module.

7. Use urllib to download a web page

In this section, we will use urllib to download a web page.

The urllib library is Python’s standard library, so you don’t need to install it.

The following lines of code can easily download a web page:

使用 Python 下载的11种姿势,一种比一种高级

Here specify what you want to save the file for and the URL of where you want to store it .

使用 Python 下载的11种姿势,一种比一种高级

In this code, we use the urlretrieve method and pass the URL of the file, and the path to save the file. The file extension will be .html.

8. Downloading through a proxy

If you need to use a proxy to download your files, you can use the ProxyHandler of the urllib module. Please look at the following code:

使用 Python 下载的11种姿势,一种比一种高级

In this code, we create the proxy object and open the proxy by calling urllib's build_opener method and pass in the proxy object . Then we create a request to get the page.

In addition, you can also use the requests module as described in the official documentation:

使用 Python 下载的11种姿势,一种比一种高级

You only need to import the requests module and create your proxy object. Then, you can get the file.

9. Using urllib3

urllib3 is an improved version of the urllib module. You can download and install it using pip:

使用 Python 下载的11种姿势,一种比一种高级

We will use urllib3 to get a web page and store it in a text file.

Import the following modules:

使用 Python 下载的11种姿势,一种比一种高级

When processing files, we use the shutil module.

Now, we initialize the URL string variable like this:

使用 Python 下载的11种姿势,一种比一种高级

Then, we use urllib3’s PoolManager, which keeps track of the necessary connection pools.

使用 Python 下载的11种姿势,一种比一种高级

Create a file:

使用 Python 下载的11种姿势,一种比一种高级

Finally, we send a GET request to get the URL and open a file, Then write the response to the file:

使用 Python 下载的11种姿势,一种比一种高级

10. Download files from S3 using Boto3

To download files from Amazon S3, you can use the Python boto3 module .

Before you begin, you need to install the awscli module using pip:

使用 Python 下载的11种姿势,一种比一种高级

For AWS configuration, run the following command:

使用 Python 下载的11种姿势,一种比一种高级

Now, enter your details by pressing the following command:

使用 Python 下载的11种姿势,一种比一种高级

To download files from Amazon S3, you need to import boto3 and botocore. Boto3 is an Amazon SDK that allows Python to access Amazon web services (such as S3). Botocore provides a command line service for interacting with Amazon web services.

Botocore comes with awscli. To install boto3, run the following command:

使用 Python 下载的11种姿势,一种比一种高级

Now, import these two modules:

使用 Python 下载的11种姿势,一种比一种高级

From Amazon When downloading a file, we need three parameters:

  • Bucket name
  • The name of the file you need to download
  • The name of the file after downloading

Initialize variables:

使用 Python 下载的11种姿势,一种比一种高级

Now, we initialize a variable to use the session’s resources. To do this, we will call boto3's resource() method and pass in the service, which is s3:

使用 Python 下载的11种姿势,一种比一种高级

Finally, use the download_file method to download the file and pass in the variable:

使用 Python 下载的11种姿势,一种比一种高级

11. Using asyncio

The asyncio module is mainly used to handle system events. It works around an event loop that waits for an event to occur and then reacts to that event. The reaction can be to call another function. This process is called event processing. The asyncio module uses coroutines for event handling.

To use asyncio event handling and coroutine functionality, we will import the asyncio module:

使用 Python 下载的11种姿势,一种比一种高级

Now, define the asyncio coroutine method like this:

使用 Python 下载的11种姿势,一种比一种高级

The keyword async indicates that this is a native asyncio coroutine. Inside the coroutine, we have an await keyword, which returns a specific value. We can also use return keyword.

Now, let’s create a piece of code to download a file from a website using a coroutine:

使用 Python 下载的11种姿势,一种比一种高级

In this code, we create an asynchronous coroutine function , which will download our file and return a message.

Then, we use another asynchronous coroutine to call main_func, which will wait for the URL and form all the URLs into a queue. asyncio's wait function waits for the coroutine to complete.

Now, in order to start the coroutine, we have to put the coroutine into the event loop using asyncio's get_event_loop() method, and finally, we execute the event loop using asyncio's run_until_complete() method.

Downloading files using Python is fun. Hope this tutorial is useful to you!

The above is the detailed content of 11 postures downloaded using Python, each more advanced than the last. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft