對(duì)上篇文章進(jìn)行優(yōu)化
并且以日期加上獲取時(shí)間進(jìn)行命名
如
直接上代碼
- 導(dǎo)入需要的庫
from bs4 import BeautifulSoup
import requests
import time
import datetime
- 獲取headers
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/+'
'537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safa+'
'ri/537.36 Edg/81.0.416.64'
}
- 定義一個(gè)抓取函數(shù)
def getOnePage(url):
res = requests.get(url, headers=headers).text
soup = BeautifulSoup(res, 'lxml')
link = soup.find('link').get('href')
link = 'https://cn.bing.com/'+link
return link
獲取圖片url
- 獲取當(dāng)前時(shí)間并且返回格式
def getTime():
local_time = time.strftime("日期%Y-%m-%d獲取時(shí)間%H-%M", time.localtime())
return local_time
- 進(jìn)行文件寫入
def writeToSave(link):
name = str(getTime()) + '.jpg'
print(name)
with open(name, 'wb') as f:
f.write(requests.get(link, headers=headers).content)
f.close()
print(str(datetime.date.today())+"的圖片保存成功")
- main函數(shù):
def main():
url = 'https://cn.bing.com/?wlexpsignin=1&mkt=zh-CN'
writeToSave(getOnePage(url))
if __name__ == '__main__':
main()
日期獲取函數(shù)duck不必闺骚,但是為了程序的分塊也就這樣寫了