欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python3如何对urllib和urllib2进行重构

时间:2021-04-10 08:51:32|栏目: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调用C/C++动态链接库的方法详解

栏    目:Python代码

下一篇:老生常谈python的私有公有属性(必看篇)

本文标题:Python3如何对urllib和urllib2进行重构

本文地址:http://www.codeinn.net/misctech/98251.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有