python3实现简单爬虫功能

本文参考虫师python2实现简单爬虫功能,并增加自己的感悟。

#coding=utf-8
import re
import urllib.request

def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    #print(type(html))
    html = html.decode('UTF-8')
    #print(html)
    return html

def getImg(html):
    reg = r'img class="BDE_Image" src="(.+?\.jpg)"'
    imgre = re.compile(reg)
    #print(type(imgre))
    #print(imgre)
    imglist = re.findall(imgre,html)
    #print(type(imglist))
    #print(imglist)
    num = 0
    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl,'D:\img\hardaway%s.jpg' %num)
        num+=1      

html = getHtml("http://tieba.baidu.com/p/1569069059")
print(getImg(html))

我这里指定的编码格式为UTF-8,根据页面源代码得出:
这就是我为何指定编码格式为UTF-8的原因

  • 再定义了一个getImg()函数,用于筛选整个页面数据中我们所需要的图片地址

  • 根据需要的图片来编写正则表达式 reg = r’img class=”BDE_Image” src=”(.+?.jpg)”’

    利用浏览器自带工具查看所需要图片的获取

  • 使用re.compile()方法把正则表达式编译成一个正则表达式对象,在一个程序中多次使用会更有效。
  • 使用re.findall()方法匹配网页数据中包含正则表达式的非重叠数据,作为字符串列表。
  • urllib.request.urlretrieve()方法,将图片下载到本地,并指定到了D盘img文件夹下

    获取到的图片


  • 上文中的例子所编写的编码格式是通过查看网页源代码的方式得知的,后来我尝试了下通过正则表达式去匹配获取charset定义的编码格式,然后指定使用匹配来的编码格式。
    def getHtml(url):
        page = urllib.request.urlopen(url)
        html = page.read()
        #print(type(html))
        rehtml = str(html)
        #print(type(rehtml))
        reg = r'content="text/html; charset=(.+?)"'
        imgre = re.compile(reg)
        imglist = re.findall(imgre,rehtml)
        print(type(imglist))
        code = imglist[0]
        print(type(code))
        html = html.decode('%s' %code)
        return html
    • 说一说这里的思路,html = page.read()方法处理后,返回的为bytes对象。而re.findall()方法是无法在一个字节对象上使用字符串模式的

      报错信息

    • 所以我新定义了一个变量rehtml,使用str()方法把html的值转为了字符串,供re.findall()方法使用

    • 定义了一个新变量code用来放编码格式的值,因为re.findall()方法获取回来的是列表类型,我需要使用的是字符串类型。


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值