1. 程式人生 > >Python爬蟲實戰(三):簡單爬取網頁圖片

Python爬蟲實戰(三):簡單爬取網頁圖片

先上程式碼:

#coding=utf-8
import urllib.request

for i in range(1,41):
   imgurl = "http://mtl.ttsqgs.com/images/img/11552/"
   imgurl += str(i) + ".jpg"
   urllib.request.urlretrieve(imgurl,'%s.jpg' % i)




這樣短短的幾行程式碼就把該網頁上的圖片全部下載下來了。怎樣,是不是超級簡單。


準備工作:
下載利器
urllib.request.urlretrieve
檢視幫助
help(urllib.request.urlretrieve)
Help on function urlretrieve in module urllib.request:

urlretrieve(url, filename=None, reporthook=None, data=None)
    Retrieve a URL into a temporary location on disk.
    
    Requires a URL argument. If a filename is passed, it is used as
    the temporary file location. The reporthook argument should be
    a callable that accepts a block number, a read size, and the
    total file size of the URL target. The data argument should be
    valid URL encoded data.
    
    If a filename is passed and the URL points to a local resource,
    the result is a copy from local file to new file.
    
    Returns a tuple containing the path to the newly created
    data file as well as the resulting HTTPMessage object.


你只需要一個下載連結並設定好引數,即可下載。


圖片分析:
網站: https://www.meitulu.com/item/11552.html
右鍵單擊正文裡的圖片  ---> 選擇   檢視影象資訊。

http://mtl.ttsqgs.com/images/img/11552/1.jpg

再看看地址框類的圖片,

http://mtl.ttsqgs.com/images/img/11552/2.jpg
http://mtl.ttsqgs.com/images/img/11552/3.jpg
http://mtl.ttsqgs.com/images/img/11552/4.jpg

這規律也是沒誰了。

網站介紹


發行機構: 貓萌榜

期刊編號: Vol.023

圖片數量: 40 張


也就是說最後一張的連結:
http://mtl.ttsqgs.com/images/img/11552/40.jpg

寫出程式碼:
for i in range(1,41):        #半開半閉區間[1,41)
   imgurl = "http://mtl.ttsqgs.com/images/img/11552/"
   imgurl += str(i) + ".jpg"   #設定好連結,進行迴圈, str(i)將型別i轉換為字串
   urllib.request.urlretrieve(imgurl,'%s.jpg' % i)     #下載到當前目錄



當然,一般都需要檢視下載進度,可以這樣修改:
#coding=utf-8
import urllib.request

for i in range(1,41):
   imgurl = "http://mtl.ttsqgs.com/images/img/11552/"
   imgurl += str(i) + ".jpg"
   print ("正在下載第{}張圖片".format(i))
   urllib.request.urlretrieve(imgurl,'%s.jpg' % i)
    
print ("OK!DownLoad ALL!")