python2和3对于爬虫时访问URL的不同

先上干货:


python2代码

#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,'C:\\360Downloads\\JPG19\\%s.jpg' % x)
        x+=1
 
 
html = getHtml("https://tieba.baidu.com/p/2460150866?pn=19")
 
print getImg(html)

python3代码

#coding=utf-8
import urllib.request
import re
 
def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read().decode("utf-8")
    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.request.urlretrieve(imgurl,'C:\\360Downloads\\JPG19\\%s.jpg' % x)
        x+=1
 
 
html = getHtml("https://tieba.baidu.com/p/2460150866?pn=19")
 
print (getImg(html))

Python2的urllib、urllib2在Python3中集合成了urllib模块,urllib库包含下面几个内容:

urllib.request
urllib.error
urllib.parse
urllib.robotparser

区别点:

Python3中urllib模块和Python2中的urllib、urllib2模块中函数区别很大。

Python2中urlopen()函数返回的是addinfourl对象:addinfourl对象实际上是一个类似于文件的对象,大概包括read()、readline()、readlines()、fileno()、close()、info()、getcode()和geturl()函数,其实这里隐藏了一个巨大的缺陷:返回的网页内容实际上已经被默认解码了,而不是由自己决定如何解码。

Python3中urlopen()函数返回的是http.client.HTTPResponse对象:http.client.HTTPResponse对象大概包括read()、readinto()、getheader()、getheaders()、fileno()、msg、version、status、reason、debuglevel和closed函数,其实一般而言使用read()函数后还需要decode()函数,这里一个巨大的优势就是:返回的网页内容实际上是没有被解码的,在read()得到内容后通过指定decode()函数参数,可以使用对应的解码方式。gbk编码的网页使用’gbk’解码,UTF-8编码的就是’utf-8’了,这样几乎可以避免所有的Python2中编码错误的问题!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值