zoukankan      html  css  js  c++  java
  • 【Python】Python简易爬虫爬取百度贴吧图片

       通过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=r'src="(https://imgsa[^>]+.(?:jpeg|jpg))"'
    #参考正则

    编写代码

    def getImg(html):
        reg=r'src="(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('
    ')
    
    def getImg(htnl):
        reg=r'src="(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()方法,直接将远程数据下载到本地

  • 相关阅读:
    sql语句之group_concat函数
    Yii2 PHPExcel在linux环境下导出报500错误
    使用 PuTTY 时遇到错误:“expected key exchange group packet from server”
    Yii2 执行Save()方法失败,却没有错误信息
    js
    导航切换到当前页的时候,会触发这个方法
    Yii2 场景scenario的应用
    Yii2 hasMany 关联后加条件
    设置Yii2发生错误返回json
    Exception 'ReflectionException' with message 'Class require does not exist'
  • 原文地址:https://www.cnblogs.com/yanglang/p/7264391.html
Copyright © 2011-2022 走看看