python下載圖片實現(xiàn)方法(超簡單)
我們有時候會需要在網(wǎng)上查找并下載圖片,當(dāng)數(shù)量比較少的時候,點擊右鍵保存,很輕松就可以實現(xiàn)圖片的下載,但是有些圖片進行了特殊設(shè)置,點擊右鍵沒有顯示保存選項,或者需要下載很多圖片,這樣的情況,寫一段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
頁面數(shù)據(jù)抓取過程定義了getHtml()函數(shù),其作用是給getHtml()傳遞一個網(wǎng)址,最終進行整個頁面的下載。
二、頁面數(shù)據(jù)篩選
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)
頁面數(shù)據(jù)篩選中,定義了一個新的函數(shù)getImg(),該函數(shù)的功能是篩選出.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循環(huán)獲得所有符合條件的圖片網(wǎng)址,并采用urllib.urlretrieve()方法,將遠程數(shù)據(jù)下載到本地,并重新命名!
以下是補充
如下所示:
import urllib.request
response = urllib.request.urlopen('http://www.dhdzp.com/g/500/600')
cat_img = response.read()
with open('cat_500_600.jpg','wb') as f:
f.write(cat_img)
urlopen()括號里既可以是一個字符串也可以是一個request對象,當(dāng)傳入字符串的時候會轉(zhuǎn)換成一個request對象,因此代碼
response = urllib.request.urlopen('http://www.dhdzp.com/g/500/600') 也可以寫成
req = urllib.request.Request('http://www.dhdzp.com/g/500/600')
1、response = urllib.request.urlopen(req)
2、responce還有g(shù)eturl,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下載圖片實現(xiàn)方法(超簡單)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Numpy中如何創(chuàng)建矩陣并等間隔抽取數(shù)據(jù)
這篇文章主要介紹了Numpy中如何創(chuàng)建矩陣并等間隔抽取數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
python中torch.load中的map_location參數(shù)使用
在PyTorch中,torch.load()函數(shù)是用于加載保存模型或張量數(shù)據(jù)的重要工具,map_location參數(shù)為我們提供了極大的靈活性,具有一定的參考價值,感興趣的可以了解一下2024-03-03
基于python代碼實現(xiàn)簡易濾除數(shù)字的方法
今天小編就為大家分享一篇基于python代碼實現(xiàn)簡易濾除數(shù)字的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python神經(jīng)網(wǎng)絡(luò)pytorch中BN運算操作自實現(xiàn)
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)pytorch中BN運算操作自實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

