我們有時候會需要在網上查找并下載圖片,當數量比較少的時候,點擊右鍵保存,很輕松就可以實現圖片的下載,但是有些圖片進行了特殊設置,點擊右鍵沒有顯示保存選項,或者需要下載很多圖片,這樣的情況,寫一段Python爬蟲代碼就可以輕松解決!
一、頁面抓取
#coding=utf-8 import urllib def getHtml(url): page = urllib.urlopen(url) html = page.read() return html html = getHtml("https://tieba.baidu.com/p/5582243679") print html
頁面數據抓取過程定義了getHtml()函數,其作用是給getHtml()傳遞一個網址,最終進行整個頁面的下載。
二、頁面數據篩選
import re import urllib def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) return imglist html = getHtml("https://tieba.baidu.com/p/5582243679") print getImg(html)
頁面數據篩選中,定義了一個新的函數getImg(),該函數的功能是篩選出.jpg格式的圖片地址。
三、圖片下載
#coding=utf-8 import urllib import re def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1 html = getHtml("https://tieba.baidu.com/p/5582243679") print getImg(html)
通過for循環獲得所有符合條件的圖片網址,并采用urllib.urlretrieve()方法,將遠程數據下載到本地,并重新命名!
以下是補充
如下所示:
import urllib.request response = urllib.request.urlopen('//www.jb51.net/g/500/600') cat_img = response.read() with open('cat_500_600.jpg','wb') as f: f.write(cat_img)
urlopen()括號里既可以是一個字符串也可以是一個request對象,當傳入字符串的時候會轉換成一個request對象,因此代碼
response = urllib.request.urlopen('//www.jb51.net/g/500/600') 也可以寫成
req = urllib.request.Request('//www.jb51.net/g/500/600')
1、response = urllib.request.urlopen(req)
2、responce還有geturl,info,getcode方法
代碼with open('cat_500_600.jpg','wb') as f:
f.write(cat_img)等價于
1、f = open('cat_500_600.jpg','wb')
2、try:
3、 data = f.write(cat_img)
4、finally:
5、 f.close()
以上這篇python下載圖片實現方法(超簡單)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
