码迷,mamicode.com
首页 > 编程语言 > 详细

Python简易爬虫爬取百度贴吧图片

时间:2017-07-30 00:56:52      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:解决   网址   color   正则表达式   find   编写   eth   admin   utf-8   

  

   通过python 来实现这样一个简单的爬虫功能,把我们想要的图片爬取到本地。(Python版本为3.6.0)

一.获取整个页面数据

  

def getHtml(url):
    page=urllib.request.urlopen(url)
    html=page.read()
    return html

 说明: 

  向getHtml()函数传递一个网址,就可以把整个页面下载下来.
  urllib.request 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据.

 

二.筛选页面中想要的数据

  在百度贴吧找到了几张漂亮的图片,想要下载下来.使用火狐浏览器,在图片位置鼠标右键单单击有查看元素选项,点进去之后就会进入开发者模式,并且定位到图片所在的前段代码

技术分享

 

 

现在主要观察图片的正则特征,编写正则表达式.

reg=rsrc="(https://imgsa[^>]+\.(?:jpeg|jpg))"
#参考正则

编写代码

def getImg(html):
    reg=rsrc="(https://imgsa[^>]+\.(?:jpeg|jpg))"
    imgre = re.compile(reg)
    imglist = re.findall(imgre,html.decode(utf-8))
    return imglist

说明:

   re.compile() 可以把正则表达式编译成一个正则表达式对象.

   re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。

      运行脚本将得到整个页面中包含图片的URL地址。

三.将页面筛选的数据保存到本地

  编写一个保存的函数

def saveFile(x):
    if not os.path.isdir(path):
        os.makedirs(path)
    t = os.path.join(path,%s.img%x)
    return  t

 

完整代码:

‘‘‘
Created on 2017年7月15日

@author: Administrator
‘‘‘
import urllib.request,os
import re

def getHtml(url):
    page=urllib.request.urlopen(url)
    html=page.read()
    return html

path=D:/workspace/Python1/reptile/__pycache__/img

def saveFile(x):
    if not os.path.isdir(path):
        os.makedirs(path)
    t = os.path.join(path,%s.img%x)
    return  t

html=getHtml(https://tieba.baidu.com/p/5248432620)
 
print(html)

print(\n)

def getImg(htnl):
    reg=rsrc="(https://imgsa[^>]+\.(?:jpeg|jpg))"
    imgre=re.compile(reg)
    imglist=re.findall(imgre,html.decode(utf-8))
    x=0
    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl,saveFile(x))
        print(imgurl)
        x+=1
        if x==23:
            break
    print(x)
    return imglist

getImg(html)
print(end)

 核心是用到了urllib.request.urlretrieve()方法,直接将远程数据下载到本地

最后,有点问题还没有完全解决,这里也向大家请教一下.

  当下载图片超过23张时会报错:

    urllib.error.HTTPError: HTTP Error 500: Internal Server Error
  不知道是什么问题,求助.

Python简易爬虫爬取百度贴吧图片

标签:解决   网址   color   正则表达式   find   编写   eth   admin   utf-8   

原文地址:http://www.cnblogs.com/fyqx/p/7257976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!