python爬虫简单的抓页面图片并保存到本地

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Chaoren666/article/details/53488083
1、首先注意编码,设置为utf-8
   #coding=utf-8
	或者
   #-*-conding:UTF-8 -*-
 
 
  先抓取页面信息
#coding=utf-8
import urllib
import re
#py抓取页面图片并保存到本地
def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html
print html
#获取页面信息
html = getHtml("http://tieba.baidu.com/p/2460150866")

然后会出来一堆html代码 CSS代码 JS代码。这样页面你就拿到了

接下来呢,咱们去抓取这个页面的图片
#coding=utf-8
import urllib
import re
#py抓取页面图片并保存到本地

#获取页面信息
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("http://tieba.baidu.com/p/2460150866")

print getImg(html)
然后大家可以看到了,图片已经全部抓取到了

最后咱们把抓到的图片保存到本地

#coding=utf-8
import urllib
import re
#py抓取页面图片并保存到本地

#获取页面信息
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
#循环把图片存到本地
    x = 0
    for imgurl in imglist:
        #保存到本地
        urllib.urlretrieve(imgurl,'/Applications/MAMP/image/%s.jpg' % x)
        x+=1

html = getHtml("http://tieba.baidu.com/p/2460150866")

print getImg(html)
为了方便管理,并且整洁,给图片重新命名为数字了

这样呢,就简单的用python实现了爬虫。

 

猜你喜欢

转载自blog.csdn.net/Chaoren666/article/details/53488083