好了,咱們這個實例要求實現的功能是爬取網頁上的圖片並下載到本地,全部相關的知識已經講解完了
爲了方便代碼的編寫,咱們把流程分析再細緻一些:
1. 傳入極視界首頁網址(url),爬取極視界首頁的網頁源碼,並使用RE獲取相冊的網址和相冊的名稱
2. 相冊的網址當成(info_url)傳入來爬取相冊的源碼,並使用RE將源碼中的圖片的網址(img_url)找出來
3. 相冊的名稱用來建立文件夾,將圖片下載放到對應的文件夾中
代碼的編寫能夠有不少種,這裏貼上我寫的代碼:
html
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = '217小月月坑' ''' 網頁跳轉,相冊圖片下載 ''' import urllib import urllib2 import re import os # url是極視界首頁網址 url = 'http://product.yesky.com/more/506001_31372_photograph_1.shtml' user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' headers = {'User-Agent':user_agent} try: request = urllib2.Request(url,headers=headers) response = urllib2.urlopen(request) conents = response.read().decode("gbk") pattern = re.compile(r'<dt><a href="(.*?)" title="(.*?)"',re.S) items = re.findall(pattern,conents) for info_url in items: print info_url[0],info_url[1] path = r'/home/ym/test/'+info_url[1] os.mkdir(path) # info_url是每個相冊的網址 info_response = urllib2.urlopen(info_url[0]) info_conents = info_response.read().decode("gbk") info_pattern = re.compile(r'<li.*?<img src="(.*?)"',re.S) img_urls = re.findall(info_pattern,info_conents) i = 1 for img_url in img_urls: # img_url 是圖片的地址 print img_url img_path = path+'/'+str(i) i+=1 urllib.urlretrieve(img_url,img_path) print u'圖片'+img_path+u'下載完成' except urllib2.URLError,e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): e.reason