python爬取網頁圖片
阿新 • • 發佈:2017-08-02
ima com col list https pytho 表達式 images 5%
在Python中使用正則表達式,一個小小的爬蟲,抓取百科詞條網頁的jpg圖片。下面就是我的代碼,作為參考:
#coding=utf-8 # __author__ = ‘Hinfa‘ import re import os from urllib import request as req url=‘https://baike.baidu.com/item/%E5%B9%BF%E5%B7%9E/72101?fr=aladdin‘ path=‘Test//百科廣州圖片2‘ os.mkdir(path) fo=open(path+‘//filecatalog.txt‘,‘w+‘) fo.write(‘爬取jpg目錄:‘) page=req.urlopen(url) html=page.read().decode(‘utf-8‘) jpgre=re.compile(r‘https.*?\.jpg‘) jpglist=re.findall(jpgre,html) i=0 for jpg in jpglist: jpg=re.sub(r‘\\\/‘,‘/‘,jpg) print(jpg) filepath=path+‘//%d.jpg‘%i fo.write(‘\n‘+jpg) req.urlretrieve(jpg,filepath) i+=1 fo.write(‘\n‘+‘爬取共計‘+str(i)+‘個‘) fo.flush() fo.close()
程序運行結果:
然後打開目錄文件裏生成的filecatalog.txt文件,爬取的內容如下:
目錄地址下載的圖片:
第一次爬蟲,很興奮,也覺得很神奇:-)
python爬取網頁圖片