zoukankan      html  css  js  c++  java
  • 2,urllib库-网络请求

    2,Urllib库使用-网络请求

    URL 处理模块

    1. 项目列表urllib 是一个收集了多个用到 URL 的模块的包:
    2. 项目列表urllib.request 打开和读取 URL
    3. 项目列表urllib.error 包含 urllib.request 抛出的异常
    4. 项目列表urllib.parse 用于解析 URL
    5. 项目列表urllib.robotparser 用于解析 robots.txt 文件

    发起请求

    urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
    
    #参数描述
    第一个参数 String 类型的地址或者一个Request 对象
    data 是 bytes 类型的内容,可通过 bytes()函数转为化字节流。它也是可选参数。使用 data 参数,请求方式变成以 POST 方式提交表单。使用标准格式是application/x-www-form-urlencoded
    timeout 参数是用于设置请求超时时间。单位是秒。
    cafile和capath代表 CA 证书和 CA 证书的路径。如果使用HTTPS则需要用到。
    context参数必须是ssl.SSLContext类型,用来指定SSL设置
    cadefault参数已经被弃用,可以不用管了。
    该方法也可以单独传入urllib.request.Request对象
    该函数返回结果是一个http.client.HTTPResponse对象
    

    简单抓取网页

    import urllib.request
    
    url = "http://tieba.baidu.com"
    response = urllib.request.urlopen(url)
    html = response.read()         # 获取到页面的源代码
    print(html.decode('utf-8'))    # 转化为 utf-8 编码
    

    设置请求超时

    请求由于网络原因无法得到响应,设置超时时间,选择直接丢弃该请求或者再请求一次.

    import urllib.request
    
    url = "http://tieba.baidu.com"
    response = urllib.request.urlopen(url, timeout=1)
    print(response.read().decode('utf-8'))
    

    对超时的抓取

    import socket
    import urllib.request
    import urllib.error
    
    try:
        response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
    except urllib.error.URLError as e:
        if isinstance(e.reason, socket.timeout):
            print('TIME OUT')
    

    使用data参数提交

    使用后使用POST 方式提交了数据

    import urllib.parse
    import urllib.request
    
    url = "http://127.0.0.1:8000/book"
    params = {
      'name':'浮生六记',
      'author':'沈复'
    }
    
    data = bytes(urllib.parse.urlencode(params), encoding='utf8')
    response = urllib.request.urlopen(url, data=data)
    print(response.read().decode('utf-8'))
    

    params 需要被转码成字节流。而 params 是一个字典。我们需要使用 urllib.parse.urlencode() 将字典转化为字符串。再使用 bytes() 转为字节流。最后使用 urlopen() 发起请求,请求是模拟用 POST 方式提交表单数据

    使用Request

    urlopen() 方法提供简单的请求发起.Request 可以添加请求头(headers),指定请求方式
    Request 的构造方法:

    urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
    
    #参数说明
    url 参数是请求链接,这个是必传参数,其他的都是可选参数。
    data 参数跟 urlopen() 中的 data 参数用法相同。
    headers 参数是指定发起的 HTTP 请求的头部信息。headers 是一个字典。它除了在 Request 中添加,还可以通过调用 Reques t实例的 add_header() 方法来添加请求头。
    origin_req_host 参数指的是请求方的 host 名称或者 IP 地址。
    unverifiable 参数表示这个请求是否是无法验证的,默认值是False。意思就是说用户没有足够权限来选择接收这个请求的结果。例如我们请求一个HTML文档中的图片,但是我们没有自动抓取图像的权限,我们就要将 unverifiable 的值设置成 True。
    method 参数指的是发起的 HTTP 请求的方式,有 GET、POST、DELETE、PUT等
    

    简单使用 Request

    伪装使用User_Agent

    import urllib.request
    
    url = "http://tieba.baidu.com/"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
    }
    request = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(request)
    print(response.read().decode('utf-8'))
    

    Request 高级用法

    在请求中添加代理、处理请求的 Cookies,我们需要用到Handler和OpenerDirector

    1) Handler

    Handler 的中文意思是处理者、处理器。 Handler 能处理请求(HTTP、HTTPS、FTP等)中的各种事情。它的具体实现是这个类 urllib.request.BaseHandler。它是所有的 Handler 的基类,其提供了最基本的Handler的方法,例如default_open()、protocol_request()等。
    继承 BaseHandler 有很多个,我就列举几个比较常见的类:

    ProxyHandler:为请求设置代理
    HTTPCookieProcessor:处理 HTTP 请求中的 Cookies
    HTTPDefaultErrorHandler:处理 HTTP 响应错误。
    HTTPRedirectHandler:处理 HTTP 重定向。
    HTTPPasswordMgr:用于管理密码,它维护了用户名密码的表。
    HTTPBasicAuthHandler:用于登录认证,一般和 HTTPPasswordMgr 结合使用

    2) OpenerDirector

    对于 OpenerDirector,我们可以称之为 Opener。我们之前用过 urlopen() 这个方法,实际上它就是 urllib 为我们提供的一个Opener。那 Opener 和 Handler 又有什么关系?opener 对象是由 build_opener(handler) 方法来创建出来 。我们需要创建自定义的 opener,就需要使用 install_opener(opener)方法。值得注意的是,install_opener 实例化会得到一个全局的 OpenerDirector 对象

    使用代理

    import urllib.request
    
    url = "http://tieba.baidu.com/"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
    }
    
    proxy_handler = urllib.request.ProxyHandler({
        'http': 'web-proxy.oa.com:8080',
        'https': 'web-proxy.oa.com:8080'
    })
    opener = urllib.request.build_opener(proxy_handler)
    urllib.request.install_opener(opener)
    
    request = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(request)
    print(response.read().decode('utf-8'))
    

    认证登录

    import urllib.request
    
    url = "http://tieba.baidu.com/"
    user = 'user'
    password = 'password'
    pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    pwdmgr.add_password(None,url ,user ,password)
    
    auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
    opener = urllib.request.build_opener(auth_handler)
    response = opener.open(url)
    print(response.read().decode('utf-8'))
    

    cookies设置

    如果请求的页面每次需要身份验证,我们可以使用 Cookies 来自动登录,免去重复登录验证的操作。获取 Cookies 需要使用 http.cookiejar.CookieJar() 实例化一个 Cookies 对象。再用 urllib.request.HTTPCookieProcessor 构建出 handler 对象。最后使用 opener 的 open() 函数即可

    import http.cookiejar
    import urllib.request
    
    url = "http://tieba.baidu.com/"
    fileName = 'cookie.txt'
    
    cookie = http.cookiejar.CookieJar()
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    response = opener.open(url)
    
    f = open(fileName,'a')
    for item in cookie:
        f.write(item.name+" = "+item.value+'
    ')
    f.close()
    

    HTTPResponse

    使用 urllib.request.urlopen() 或者 opener.open(url) 返回结果是一个 http.client.HTTPResponse 对象。它具有msg、version、status、reason、debuglevel、closed等属性以及read()、readinto()、getheader(name)、getheaders()、fileno()等函数

    错误解析

    异常处理主要用到两个类,urllib.error.URLError和urllib.error.HTTPError
    1,URLError
    URLError 是 urllib.error 异常类的基类, 可以捕获由urllib.request 产生的异常。它具有一个属性reason,即返回错误的原因

    import urllib.request
    import urllib.error
    
    url = "http://www.google.com"
    try:
        response = request.urlopen(url)
    except error.URLError as e:
        print(e.reason)
    

    2,HTTPError
    HTTPError 是 UEKRrror 的子类,专门处理 HTTP 和 HTTPS 请求的错误。它具有三个属性。
    1)code:HTTP 请求返回的状态码。
    2)renson:与父类用法一样,表示返回错误的原因。
    3)headers`:HTTP 请求返回的响应头信息

    import urllib.request
    import urllib.error
    
    url = "http://www.google.com"
    try:
        response = request.urlopen(url)
    except error.HTTPError as e:
       print('code: ' + e.code + '
    ')
       print('reason: ' + e.reason + '
    ')
       print('headers: ' + e.headers + '
    ')
    

    响应

    import urllib.request
    
    response = urllib.request.urlopen('https://www.python.org')
    print(type(response))
    
    
    #结果为:<class 'http.client.httpresponse'="">
    
    

    可以通过response.status、response.getheaders().response.getheader("server"),获取状态码以及头部信息response.read()获得的是响应体的内容

  • 相关阅读:
    剑指Offer_08_跳台阶
    剑指Offer_07_斐波那契数列
    HDU 4283 You Are the One
    1B. Spreadsheets
    1A Theatre Square
    HDU 2476 String painter(记忆化搜索, DP)
    LightOJ 1422 Halloween Costumes(记忆化搜索)
    POJ 1651 Multiplication PuzzleDP方法:
    POJ 2955 Brackets (区间DP)
    HDU 5452 Minimum Cut
  • 原文地址:https://www.cnblogs.com/g2thend/p/12452168.html
Copyright © 2011-2022 走看看