天天看點

Python下載下傳圖檔Python下載下傳圖檔

Python下載下傳圖檔

工具:Pycharm,Win10,Python3.6.4

這次就是一個很簡單的案例,做一個圖檔爬蟲。思路就是擷取圖檔連結,然後下載下傳圖檔,儲存檔案,子產品代碼如下。

# 根據圖檔連結下載下傳
def download_image(img_url, i):
    print('正在下載下傳', img_url)
    try:
        response = requests.get(img_url, headers=headers)
        # if response.status_code == 200:
        save_image(response.content, i)  # content和text的差別是content傳回的是二進制内容,傳回的是圖檔就用content
        # return response.text
        return None
    except RequestException:
        print('請求圖檔出錯', url)
        return None


# 寫入圖檔
def save_image(content, i):
    with open(str(i) + '.png', 'wb') as f:
        f.write(content)
        f.close()