zoukankan      html  css  js  c++  java
  • urllib的各种方法

    第一种请求头的方式

    import urllib.request
    
    from urllib import request, parse
    url = 'http://httpbin.org/post'
    headers = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
        'Host': 'httpbin.org'
    }
    dict = {
        'name': 'zhaofan'
    }
    data = bytes(parse.urlencode(dict), encoding='utf8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))

    第二种请求头的方式

    from urllib import request, parse
    
    url = 'http://httpbin.org/post'
    dict = {
        'name': 'Germey'
    }
    data = bytes(parse.urlencode(dict), encoding='utf8')
    req = request.Request(url=url, data=data, method='POST')
    req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))   #decode可以将结果格式化显示



    设置代理
    通过rulllib.request.ProxyHandler()可以设置代理,
    网站它会检测某一段时间某个IP 的访问次数,
    如果访问次数过多,它会禁止你的访问,
    所以这个时候需要通过设置代理来爬取数据

    import urllib.request
    
    proxy_handler = urllib.request.ProxyHandler({
        'http': 'http://127.0.0.1:9743',   # 访问哪个网站格式http,https选用其中对应的一哥
        'https': 'https://127.0.0.1:9743'
    })
    opener = urllib.request.build_opener(proxy_handler)
    response = opener.open('http://httpbin.org/get')
    print(response.read())

    cookie,HTTPCookiProcessor

    cookie中保存中我们常见的登录信息,
    有时候爬取网站需要携带cookie信息访问,
    这里用到了http.cookijar,用于获取cookie以及存储cookie

    import http.cookiejar, urllib.request
    cookie = http.cookiejar.CookieJar()
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    for item in cookie:
        print(item.name+"="+item.value)

    同时cookie可以写入到文件中保存,有两种方式http.cookiejar.MozillaCookieJar和http.cookiejar.LWPCookieJar(),当然你自己用哪种方式都可以

    http.cookiejar.MozillaCookieJar()方式

    import http.cookiejar, urllib.request
    filename = "cookie.txt"
    cookie = http.cookiejar.MozillaCookieJar(filename)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    cookie.save(ignore_discard=True, ignore_expires=True)

    http.cookiejar.LWPCookieJar()方式

    import http.cookiejar, urllib.request
    filename = 'cookie.txt'
    cookie = http.cookiejar.LWPCookieJar(filename)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    cookie.save(ignore_discard=True, ignore_expires=True)

    同样的如果想要通过获取文件中的cookie获取的话可以通过load方式,
    当然用哪种方式写入的,就用哪种方式读取。

    import http.cookiejar, urllib.request
    cookie = http.cookiejar.LWPCookieJar()
    cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    print(response.read().decode('utf-8'))

    异常处理在很多时候我们通过程序访问页面的时候,有的页面可能会出现错误,类似404,500等错误这个时候就需要我们捕捉异常,下面先写一个简单的例子

    from urllib import request,error
    
    try:
        response = request.urlopen("http://pythonsite.com/1111.html")
    except error.URLError as e:
        print(e.reason)

    上述代码访问的是一个不存在的页面,通过捕捉异常,我们可以打印异常错误

    这里我们需要知道的是在urllb异常这里有两个个异常错误:
    URLError,HTTPError,HTTPError是URLError的子类

    URLError里只有一个属性:reason,即抓异常的时候只能打印错误信息,类似上面的例子

    HTTPError里有三个属性:code,reason,headers,即抓异常的时候可以获得code,reson,headers三个信息,例子如下:

    from urllib import request,error
    try:
        response = request.urlopen("http://pythonsite.com/1111.html")
    except error.HTTPError as e:
        print(e.reason, "error.HTTPError")
        print(e.code, "error.HTTPError")
        print(e.headers, "error.HTTPError")
    except error.URLError as e:
        print(e.reason,"error.URLError")
    
    else:
        print("reqeust successfully")

    同时,e.reason其实也可以在做深入的判断,例子如下:

    import socket
    
    from urllib import error,request
    
    try:
        response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)  # 时间太短了
    except error.URLError as e:
        print(type(e.reason))
        if isinstance(e.reason,socket.timeout):
            print("time out")

    URL解析

    urlparseThe URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

    功能一:

    from urllib.parse import urlparse
    
    result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
    print(result)

    这里就是可以对你传入的url地址进行拆分同时我们是可以指定协议类型:result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")这样拆分的时候协议类型部分就会是你指定的部分,当然如果你的url里面已经带了协议,你再通过scheme指定的协议就不会生效

     

    urlunparse

    其实功能和urlparse的功能相反,它是用于拼接,例子如下

    from urllib.parse import urlunparse
    
    data = ['http','www.baidu.com','index.html','user','a=123','commit']
    print(urlunparse(data))  #输出http://www.baidu.com/index.html;user?a=123#commit


    urljoin

    这个的功能其实是做拼接的,例子如下:

    from urllib.parse import urljoin
    
    # print(urljoin('http://www.baidu.com', 'FAQ.html'))
    print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))
    print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))
    print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))
    print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.com/index.php'))
    print(urljoin('http://www.baidu.com', '?category=2#comment'))
    print(urljoin('www.baidu.com', '?category=2#comment'))
    print(urljoin('www.baidu.com#comment', '?category=2'))

    从拼接的结果我们可以看出,拼接的时候后面的优先级高于前面的url

    urlencode
    这个方法可以将字典转换为url参数,例子如下

    from urllib.parse import urlencode
    
    params = {
        "name":"zhaofan",
        "age":23,
    }
    base_url = "http://www.baidu.com?"
    
    url = base_url+urlencode(params)
    print(url)   # 输出结果为http://www.baidu.com?name=zhaofan&age=23
  • 相关阅读:
    基于Proxy的小程序状态管理
    还不会正则表达式?看这篇!
    Fundebug前端JavaScript插件更新至1.8.2,修复2个小BUG
    JavaScript深入浅出第1课:箭头函数中的this究竟是什么鬼?
    5种处理Vue异常的方法
    重构:一项常常被忽略的基本功
    SQL Server中使用SQL语句关闭数据库连接和删除数据库文件
    SQL Server使用加密连接SSL/TLS (转载)
    SQL Server使用sp_executesql在存储过程中执行多个批处理
    How to call a stored procedure in EF Core 3.0 via FromSqlRaw(转载)
  • 原文地址:https://www.cnblogs.com/cjj-zyj/p/10025957.html
Copyright © 2011-2022 走看看