import requests
import time
import os
raw_url = 'https://www.bilibili.com/index/recommend.json'
headers = {
'Host':'www.bilibili.com',
'X - Requested - With': 'XMLHttpRequest',
'User - Agent':
' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
def save_image(url):
filename = url.lstrip('http://').replace('.','').replace('/','').rstrip('jpg')+'.jpg'
try:
res = requests.get(url, headers=headers)
if res.ok:
img = res.content
if not os.path.exists(filename):
with open(filename,'wb') as f:
f.write(img)
except Exception:
print('Failed to load the picture')
def get_json():
try:
res = requests.get(raw_url, headers=headers)
if res.ok:
return res.json()
else:
print('not ok')
return False
except Exception as e:
print('Error here :\t',e)
def json_parser(json):
if json is not None:
news_list = json.get('list')
if not news_list:
return False
for news_item in news_list:
pic_url = news_item.get('pic')
yield pic_url
def worker():
raw_json = get_json()
print(raw_json)
urls = json_parser(raw_json)
for url in urls:
save_image(url)
if __name__ == '__main__':
worker()
你这函数只在创建,也没看你调用啊,而且你都写多个函数了,为什么不每个函数独立写