1. 程式人生 > >簡單python爬蟲淘寶圖片+介面程式設計+打包成exe

簡單python爬蟲淘寶圖片+介面程式設計+打包成exe

原始碼解析

新建GetImg.py檔案:

第一步:編寫爬蟲程式碼

import re
import urllib.request
def getHtml(url='') :
    page = urllib.request.urlopen(url)
    html = page.read().decode('GBK') #解析網頁原始碼
    return html


#print(html)

def getImg(html):
    #https://cbu01.alicdn.com/img/ibank/2016/693/443/3382344396_1109687136.jpg
    #reg = r'https://.*\.?alicdn\.com[^"]+\.jpg'
    reg = r'//[\w]*\.?alicdn\.com[^"\']+\.jpg'#正則表示式,搜尋匹配欄位
    imgre = re.compile(reg)
    imglist = re.findall(imgre,html)
    print(len(imglist))
    x = 1
    for imgurl in imglist:
        print(imgurl)
        imgurl = 'https:' + imgurl
        urllib.request.urlretrieve(imgurl,'save\\%s.jpg' %x) #按順序儲存在save資料夾
        x+=1

def DownLoadImg(url):
    html = getHtml(url)
    getImg(html)
通過呼叫DownLoadImg()函式,即可下載所有.jpg格式的圖片
例如:DownLoadImg('https://detail.1688.com/offer/523861658213.htmlspm=b26110380.8015204.xshy005.37.q3aAzE')

第二步:編寫介面

class Application(Frame):
         def __init__(self, master=None):
                  Frame.__init__(self, master)
                  self.pack(fill=X,padx=100)
                  self.createWidgets()
         def createWidgets(self):
                  self.nameInput = Entry(self)
                  self.nameInput.pack(fill=X,pady=10)
                  self.nameInput.pack(fill=X,padx=5)
                  self.alertButton = Button(self, text=(' Please Input Website '), command=self.FUN)
                  self.alertButton.pack(fill=X,padx=30)
                  self.alertButton.pack(fill=X,pady=10)
         def FUN(self):
                  name = self.nameInput.get() or 'blank'
                  if name == 'blank':
                           messagebox.showinfo('Message', 'Website is invalid!')
                  else:
                           DownLoadImg(name)
                           messagebox.showinfo('Message', 'Success: see \"save\" folder')
app = Application()
app.master.title('DownLoad IMG From Web : [LSX]')
app.mainloop()
第三步:打包成exe

下載py2exe,選擇對應python版本,僅支援python3.3以上版本,3.5版本用起來有點問題,所以本文采用python3.4。

兩種方法把python程式打包成exe

1.在cmd命令視窗下,進入GetImg.py資料夾

執行

build_exe GetImg.py
生成的exe檔案被儲存在dist檔案中。

2.新建一個convert2exe.py

from distutils.core import setup  
import py2exe  
setup(windows=[{"script": "GetImg.py"}]) 
執行
python convert2exe.py py2exe

總結:

1.沒有搞清楚解析html原始碼格式,'GBK','utf-8',對於'utf-8'格式的原始碼解析總是出現錯誤

2.對於py2exe軟體,不能轉換中文字元。

3.只能解析到部分圖片,可能是正則表示式有問題。

參考: