1. 程式人生 > >Python之抓取動態網頁

Python之抓取動態網頁

python之抓取花瓣網圖片
實現方法:
1,建立一個資料夾。
2,模擬請求網路服務。
3,匹配抓取的圖片。
4,儲存。

#_*_coding:utf8_*_
import re
import os
import urllib,urllib2
import sys
reload(sys)
#建立儲存圖片資料夾
if(os.path.exists('儲存圖片檔案的名稱')==False:
     os.mkdir('儲存圖片檔案的名稱')
#模擬請求
def img():
#開啟抓取的網頁原始碼,可以看到pin_id
    pin_id=網頁中的數字
    while pin_id !=None
url='開啟網頁的網址?'+str(pin_id) try: i_header={"User-Agent":"開啟審查元素,切換到網路,可以看到此項內容,貼上複製到這裡。",、"Referer":'http://baidu.com/(其他瀏覽器)'} zq=urllib2.Requests(url,headers=i_header html=urllib2.urlopen(zq).read() zqd=re.compile('"user_id":(.*?),.+?"file":{"farm":"farm1", "bucket":"hbimg",.+?"key":"(.*?)",.+?"type":"image/(.*?)"'
,re.S) groups=re.findall(zqd,html) print "start to catch"+str(len(groups)) for att in groups: pin_id=att[0] att_url = att[1] + '_fw236' img_type = att[2] img_url='http://img.hb.aicdn.com/'+att_url if
(urllib.urlretrieve(img_url,'儲存圖片的資料夾'+att_url+'.'+img_type)): print 'download success' else: print 'downing fail' except: print 'Error' img()