欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python下載圖片實現(xiàn)方法(超簡單)

 更新時間:2017年07月21日 08:20:38   投稿:jingxian  
下面小編就為大家?guī)硪黄猵ython下載圖片實現(xiàn)方法(超簡單)。小編覺得挺不錯的,現(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.dbjr.com.cn/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.dbjr.com.cn/g/500/600') 也可以寫成

req = urllib.request.Request('http://www.dbjr.com.cn/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)文章

最新評論