python 3編寫貼吧圖片下載程式(超簡單)
阿新 • • 發佈:2018-12-19
業餘時間初學者作品,大佬勿噴,程式碼都很簡單。py檔案打包成exe教程:python3.7 打包成exe程式,程式體驗下載地址:
先上效果圖
啟動後是這樣的:
按提示輸入內容執行後是這樣的:
上程式碼(基本都是最基本的語法,不多解釋了):
import requests import os from bs4 import BeautifulSoup from pip._vendor.distlib.compat import raw_input def down(type, num, url, img_path): if type == '1': url2 = url + '&pn={}'.format(num) else: url2 = url + '?pn={}'.format(num) if not os.path.exists(img_path): os.makedirs(img_path) req = requests.get(url2) req.encoding = "utf-8" bs = BeautifulSoup(req.text, 'html.parser') img = bs(class_='BDE_Image') con = 0 if img.__len__() == 0: print("<--第{}頁無圖片,跳轉下一頁-->".format(num)) else: for xx in img: con += 1 url = xx.get('src') height = xx.get('height') width = xx.get('width') name = '\\' + str(num) + '_' + str(con) + '(' + height + 'x' + width + ')' res = requests.get(url) with open("{}{}{}".format(img_path, name, '.jpg'), 'wb')as f: f.write(res.content) print("第{}頁,第{}張,下載完畢".format(num, con)) if __name__ == '__main__': print('貼吧圖片下載工具v1.0 by wjup\n\n說明:輸入內容請按要求填寫,填錯會退出程式。' '\n請規範輸入帖子地址,像這樣-->\n只看樓主:https://tieba.baidu.com/p/3430697608?see_lz=1\n' '不是隻看樓主:https://tieba.baidu.com/p/3430697608' '\n圖片儲存路徑寫法:F:\\\image,如果不填會預設下載到E:\\\貼吧圖片 目錄下\n\n') type = raw_input('開始吧!\n\n請選擇是否為只看樓主型別的地址\n(輸入1或2即可) 1:是 2:否 :') while type.strip() == '': type = raw_input('請選擇是否為只看樓主型別的地址\n(輸入1或2即可) 1:是 2:否 :') url = raw_input('\n請輸入貼子地址:') while url.strip() == '': print('地址都不輸入,還下載個毛!') url = raw_input('請輸入貼子地址:') end_page = input('\n請輸入帖子總頁數:') if end_page.strip() == '': print('頁數為空,預設下載前3頁圖片內容') end_page = 3 img_path = raw_input('\n請輸入圖片儲存路徑(例:F:\\\image):') print('-------------下載--------------') if not img_path.strip(): print('地址為空預設儲存到 E:\\\貼吧圖片') print('-------------下載--------------\n') img_path = 'E:\\貼吧圖片' for i in range(1, int(end_page) + 1): down(type, i, url, img_path)