RandomImg/py/pic.py
2021-04-05 19:06:59 +08:00

48 lines
1.6 KiB
Python

import requests
import os
import urllib.parse as up
import time
import json
def get_pic():
try:
url = "https://www.dmoe.cc/random.php?return=json"
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36', 'Referer': 'https://img.r10086.com/'}
res = requests.get(url,headers = headers)
con = json.loads(res.content)
save(con['imgurl'],'二次元2',con['width'],con['height'])
except Exception as error:
print(error,res.content)
def save(url,path,width,height):
# print('saving',url)
filename = os.path.basename(url)
str1 = {
"url": url,
"name": filename.split('.')[0],
"format": filename.split('.')[-1],
"width": width,
"height": height
}
json_row = str(str1)
print(json_row)
if os.path.exists(path) == False:
os.makedirs(path)
if url != '' and os.path.exists(path + '/' + filename) == False:
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ch rome/89.0.4389.114 Safari/537.36',
'Referer': url}
try:
r = requests.get(url, headers=headers, timeout=2)
with open(path + '/' + filename, 'wb') as f:
f.write(r.content)
print('保存成功')
with open("images.json","a") as file:
file.write(json_row+",\n")
except Exception as error:
print('保存失败')
print(error)
if __name__ == '__main__':
while True:
get_pic()