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

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.

主站蜘蛛池模板: 山东省| 南木林县| 贺兰县| 安仁县| 大理市| 军事| 兴仁县| 六枝特区| 和政县| 雅江县| 丰都县| 闽侯县| 扎赉特旗| 招远市| 凤台县| 高要市| 锡林郭勒盟| 葵青区| 福清市| 兴业县| 香港 | 梁山县| 沧源| 辽源市| 平谷区| 宁远县| 绩溪县| 廉江市| 土默特右旗| 德江县| 静乐县| 青川县| 广宗县| 高碑店市| 大田县| 阜南县| 边坝县| 明水县| 广宁县| 虞城县| 安阳市|