zoukankan      html  css  js  c++  java
  • 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())

    参考链接:https://blog.csdn.net/weixin_43550140/article/details/84563205

  • 相关阅读:
    打开LogCat以便查看日志
    sql语句优化
    IIS部署说明
    VM上Hadoop3.1伪分布式模式搭建
    C# 程序结构
    CSS笔记1:属性定位
    VS2013 添加控制台程序
    布局 Layout
    [游泳] 游泳学习课程
    "12306"台前幕后:五年利益之争 仓促上线
  • 原文地址:https://www.cnblogs.com/lfri/p/11919593.html
Copyright © 2011-2022 走看看