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

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.

主站蜘蛛池模板: 从江县| 鲜城| 吉水县| 和平县| 大渡口区| 鸡东县| 永春县| 凌源市| 兴和县| 临江市| 教育| 彭阳县| 宁德市| 柳州市| 惠安县| 石林| 山西省| 陇川县| 城市| 河池市| 松潘县| 佛坪县| 河源市| 蕉岭县| 云龙县| 台东市| 临洮县| 肥东县| 新兴县| 吉安市| 嘉义县| 沁阳市| 牟定县| 侯马市| 楚雄市| 淮南市| 太康县| 宁城县| 大余县| 双辽市| 砀山县|