Python下載校花貼吧上面的圖片
阿新 • • 發佈:2020-08-07
# write by xdd1997 [email protected] # 2020-08-07 import time import os import winreg import requests import urllib.request from bs4 import BeautifulSoup # 獲取桌面路徑 def desktop_path(): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders') path= winreg.QueryValueEx(key, "Desktop")[0] return path # -------------遞迴建立目錄----------- def CreatPath(): path = os.path.join(desktop_path().replace('/','\\'),'校花貼吧圖片') if not os.path.exists(path): os.makedirs(path) return path for i in range(0,100,50): ## 100=50*2,表明下載2頁,可改為150,300... url= "https://tieba.baidu.com/f?kw=%E6%A0%A1%E8%8A%B1&ie=utf-8&pn={}".format(i) print(url) r = requests.get(url) demo = r.text soup = BeautifulSoup(demo, "html.parser") piclist = [] for link in soup.find_all('img'): link_list = link.get('bpic') if link_list != None: piclist.append(link_list)for http in piclist: print(http) name = time.strftime("%Y%m%d%H%M%S", time.localtime()) filesavepath = os.path.join(CreatPath(), name + '.jpg') urllib.request.urlretrieve(http, filesavepath) print('正在儲存圖片') time.sleep(1) print('下載完成')