亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2017年07月21日 08:20:38   投稿:jingxian  
下面小編就為大家?guī)硪黄猵ython下載圖片實(shí)現(xiàn)方法(超簡(jiǎn)單)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

我們有時(shí)候會(huì)需要在網(wǎng)上查找并下載圖片,當(dāng)數(shù)量比較少的時(shí)候,點(diǎn)擊右鍵保存,很輕松就可以實(shí)現(xiàn)圖片的下載,但是有些圖片進(jìn)行了特殊設(shè)置,點(diǎn)擊右鍵沒有顯示保存選項(xiàng),或者需要下載很多圖片,這樣的情況,寫一段Python爬蟲代碼就可以輕松解決!

一、頁(yè)面抓取

#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

頁(yè)面數(shù)據(jù)抓取過程定義了getHtml()函數(shù),其作用是給getHtml()傳遞一個(gè)網(wǎng)址,最終進(jìn)行整個(gè)頁(yè)面的下載。

二、頁(yè)面數(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)

頁(yè)面數(shù)據(jù)篩選中,定義了一個(gè)新的函數(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()方法,將遠(yuǎn)程數(shù)據(jù)下載到本地,并重新命名!

以下是補(bǔ)充

如下所示:

import urllib.request
response = urllib.request.urlopen('http://chabaoo.cn/g/500/600')
cat_img = response.read()

with open('cat_500_600.jpg','wb') as f:
 f.write(cat_img)

urlopen()括號(hào)里既可以是一個(gè)字符串也可以是一個(gè)request對(duì)象,當(dāng)傳入字符串的時(shí)候會(huì)轉(zhuǎn)換成一個(gè)request對(duì)象,因此代碼

response = urllib.request.urlopen('http://chabaoo.cn/g/500/600') 也可以寫成

req = urllib.request.Request('http://chabaoo.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)等價(jià)于

1、f = open('cat_500_600.jpg','wb')

2、try:

3、 data = f.write(cat_img)

4、finally:

5、 f.close()

以上這篇python下載圖片實(shí)現(xiàn)方法(超簡(jiǎn)單)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論