Python3对urllib和urllib2进行重构的方法

  介绍

小编给大家分享一下Python3对urllib和urllib2进行重构的方法,希望大家阅读完这篇文章之后都有所收获、下面让我们一起去探讨吧!

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

<李>

urllib2.urlopen()变成了urllib.request.urlopen ()

<李>

urllib2.Request()变成了urllib.request.Request ()

<李>

python2中的cookielib改为http.cookiejar。李李

<>

进口http。cookiejar代替进口cookielib

<李>

urljoin现在对应的函数是urllib.parse。李urljoin

代码如下

import  urllib.request   import  http.cookiejar      url =癶ttp://www.baidu.com"      print (& # 39;第一种方法& # 39;)   response1=urllib.request.urlopen (url)   print  (response1.getcode ())   print  (len (response1.read ()))      print (& # 39;第二种方法& # 39;)   请求=urllib.request.Request (url)   request.add_header (“user-agent"“Mozilla/5.0“) #将爬虫伪装成浏览器   response2=urllib.request.urlopen(请求)   print  (response2.getcode()) #打印状态码   print  (len (response2.read())) #打印内容长度      print (& # 39;第三种方法& # 39;)   时间=cj  http.cookiejar.CookieJar ()   时间=opener  urllib.request.build_opener (urllib.request.HTTPCookieProcessor (cj))   urllib.request.install_opener(刀)   response3=urllib.request.urlopen (url)   print  (response1.getcode ())   print  (cj),, #输出饼干   print  (response1.read ())

看完了这篇文章,相信你对“Python3对urllib和urllib2进行重构的方法”有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!

Python3对urllib和urllib2进行重构的方法