LoginSignup
0
0

[Python]画像をGETする、POSTする

Last updated at Posted at 2023-06-03

Pythonで画像をサイトから保存する、画像をサーバやAPIにpostする。

画像をGETする

reqestモジュールを使って保存する。

import requests

#画像のurlを設定
url = "https://xxx.com/yyyy/zzzzz.jpg"

#画像をGETする
response = requests.get(url)
image = response.content

#保存名を設定する
image_name = "image.jpg"

#画像を保存する
with open(image_name, "wb") as f:
    f.write(image)

応用する

import requests

#数字を設定
num = 1

#数字が10になるまで繰り替えす(10回繰り返す)
while num < 10:
    #画像のurlを設定
    url = "https://xxx.com/yyyy/" + str(num) + ".jpg"
    
    #画像をGetする
    response = requests.get(url)
    image = response.content
    
    #保存名を設定する
    image_name = str(num) + ".jpg"
    
    #画像を保存する
    with open(image_name, "wb") as f:
        f.write(image)

    #数字に+1する
    num += 1

画像をPOSTする

GETと同様に応用が可能。

import requests

#postするurlを設定
url = "https://aaa.com/bbbb/ccccc.php"

#画像を読み込む
image = "./image.jpg"
data = open(image, 'rb')
file = {'image': data}

#postする
res = requests.post(url, files=file)

#レスポンスを表示する
print(res.text) #.textはなくてもよい
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0