官术网_书友最值得收藏!

How to do it...

Let's try downloading a simple image file with the requests module. Open Python 2:

  1. As usual, import the requests library first:
>>> import requests  
  1. Create an HTTP response object by passing a URL to the get method:
>>> response = requests.get("https://rejahrehim.com/images/me/rejah.png")  
  1. Now send the HTTP request to the server and save it to a file:
>>> with open("me.png",'wb') as file:
...           file.write(response.content)

If it's a large file, the response.content will be a large string and won't be able to save all the data in a single string. Here, we use the iter_content method to load the data in chunks.

  1. Here, we can create an HTTP response object as a stream:
response = requests.get("https://rejahrehim.com/images/me/rejah.png", stream = True)
    
  1. Then, send the request and save the file with the following command:
>>> with open("me.png",'wb') as file:
...        for chunk in response.iter_content(chunk_size=1024):
...        if chunk:
...             file.write(chunk) 

This will work in Python 3. Also, make sure you install the required libraries in the Python 3 environment.

主站蜘蛛池模板: 玉林市| 渑池县| 临邑县| 龙海市| 山西省| 宝兴县| 九江县| 乌拉特前旗| 响水县| 屏东县| 大邑县| 余姚市| 赣州市| 托克托县| 双牌县| 龙泉市| 昭觉县| 广西| 康保县| 永修县| 金阳县| 剑川县| 黔东| 荥阳市| 彭州市| 沙坪坝区| 牙克石市| 沈阳市| 北安市| 双峰县| 马鞍山市| 诏安县| 三明市| 九寨沟县| 泾阳县| 华池县| 阿尔山市| 黔南| 西和县| 湛江市| 仙居县|