Python3如何对urllib和urllib2进行重构

yipeiwu_com5年前Python基础

这篇文章主要介绍了Python3如何对urllib和urllib2进行重构,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

python3对urllib和urllib2进行了重构,拆分成了urllib.request,urllib.response, urllib.parse, urllib.error等几个子模块,这样的架构从逻辑和结构上说更加合理。urllib库无需安装,python3自带。python 3.x中将urllib库和urilib2库合并成了urllib库。 其中

  • urllib2.urlopen() 变成了 urllib.request.urlopen()
  • urllib2.Request() 变成了 urllib.request.Request()
  • python2中的 cookielib 改为 http.cookiejar.
  • import http.cookiejar 代替 import cookielib
  • urljoin 现在对应的函数是 urllib.parse.urljoin

代码如下

import urllib.request
import http.cookiejar

url ="http://www.baidu.com"

print ('第一种方法')
response1=urllib.request.urlopen(url)
print (response1.getcode())
print (len(response1.read()))

print ('第二种方法')
request=urllib.request.Request(url)
request.add_header("user-agent","Mozilla/5.0")#将爬虫伪装成浏览器
response2=urllib.request.urlopen(request)
print (response2.getcode())#打印状态码
print (len(response2.read()))#打印内容长度

print ('第三种方法')
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
urllib.request.install_opener(opener)
response3=urllib.request.urlopen(url)
print (response1.getcode())
print (cj)  #输出cookie
print (response1.read())

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python第三方库h5py_读取mat文件并显示值的方法

mat数据格式是Matlab默认保存的数据格式。在Python中,我们可以使用h5py库来读取mat文件。 >>> import h5py >>>...

videocapture库制作python视频高速传输程序

videocapture库制作python视频高速传输程序

1,首先是视频数据[摄像头图像]的采集,通常可以使用vfw在vc或者vb下实现,这个库我用的不好,所以一直不怎么会用.现在我们用到的是python的videocapture库,这个库用起...

Python中使用item()方法遍历字典的例子

Python中使用item()方法遍历字典的例子

Python字典的遍历方法有好几种,其中一种是for...in,这个我就不说明,在Python了几乎随处都可见for...in。下面说的这种遍历方式是item()方法。 item() i...

python保存字符串到文件的方法

本文实例讲述了python保存字符串到文件的方法。分享给大家供大家参考。具体实现方法如下: def save(filename, contents): fh = open(fi...

Python paramiko模块使用解析(实现ssh)

开发堡垒机之前,先来学习Python的paramiko模块,该模块基于SSH用于连接远程服务器并执行相关操作 安装paramiko模块 pip3 install paramiko...