• requests库


    python中requests库使用方法详解

    官方文档

    requests的具体安装过程请看:http://docs.python-requests.org/en/latest/user/install.html#install
    requests的官方指南文档:http://docs.python-requests.org/en/latest/user/quickstart.html
    requests的高级指南文档:http://docs.python-requests.org/en/latest/user/advanced.html#advanced

    什么是Requests

    Requests 是⽤imgython语⾔编写,基于urllib,采⽤Apache2 Licensed开源协议的 HTTP 库。它⽐ urllib 更加⽅便,
    可以节约我们⼤量的⼯作,完全满⾜HTTP测试需求。

    ⼀句话——Python实现的简单易⽤的HTTP库

    安装Requests库

    进入命令行win+R执行

    命令:pip install requests

    项目导入:import requests

    各种请求方式

    直接上代码,不明白可以查看我的urllib的基本使用方法

    import requests
    
    requests.post('http://httpbin.org/post')
    requests.put('http://httpbin.org/put')
    requests.delete('http://httpbin.org/delete')
    requests.head('http://httpbin.org/get')
    requests.options('http://httpbin.org/get')
    

    这么多请求方式,都有什么含义,所以问下度娘:

    GET: 请求指定的页面信息,并返回实体主体。
    HEAD: 只请求页面的首部。
    POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
    PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
    DELETE: 请求服务器删除指定的页面。
    get 和 post比较常见 GET请求将提交的数据放置在HTTP请求协议头中
    POST提交的数据则放在实体数据中

    基本的GET请求

    import requests
    
    response = requests.get('http://httpbin.org/get')
    print(response.text)
    返回值:
    
    {
        "args": {}, 
        "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Connection": "close", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.18.4"
      }, 
      "origin": "183.64.61.29", 
      "url": "http://httpbin.org/get"
    }
    
    
    (4)、获取二进制数据
    
    记住返回值.content就ok了
    
    import requests
    
    response = requests.get("https://github.com/favicon.ico")
    print(type(response.text), type(response.content))
    print(response.text)
    print(response.content)
    

    带参数的GET请求

    将name和age传进去
    
    import requests
    
    response = requests.get("http://httpbin.org/get?name=germey&age=22")
    print(response.text)
    {
        "args": {
        "age": "22", 
        "name": "germey"
      }, 
        "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Connection": "close", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.18.4"
      }, 
      "origin": "183.64.61.29", 
      "url": "http://httpbin.org/get?name=germey&age=22"
    }
    或者使用params的方法:
    
    import requests
    
    data = {
     'name': 'germey',
     'age': 22
    }
    response = requests.get("http://httpbin.org/get", params=data)
    print(response.text)
    返回值一样
    

    返回值为二进制不必再进行展示,

    解析json

    将返回值已json的形式展示:
    
    
    import requests
    
    import json
    
    
    response = requests.get("http://httpbin.org/get")
    
    print(type(response.text))
    
    print(response.json())
    
    print(json.loads(response.text))
    
    print(type(response.json()))
    
    返回值:
    
    
    <class 'str'>
    
    {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '183.64.61.29', 'url': 'http://httpbin.org/get'}
    
    {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '183.64.61.29', 'url': 'http://httpbin.org/get'}
    
    <class 'dict'>
    

    添加headers

    有些网站访问时必须带有浏览器等信息,如果不传入headers就会报错,如下

    import requests
    
    response = requests.get("https://www.zhihu.com/explore")
    print(response.text)
    返回值:
    
    <html><body><h1>500 Server Error</h1>
    An internal server error occured.
    </body></html>
    当传入headers时:
    
    import requests
    
    headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    response = requests.get("https://www.zhihu.com/explore", headers=headers)
    print(response.text)
    成功返回网页源代码不做展示
    

    基本POST请求

    不明白见urllib的使用方法

    import requests
    
    data = {'name': 'germey', 'age': '22'}
    response = requests.post("http://httpbin.org/post", data=data)
    print(response.text)
    
    返回:
    
    {
       "args": {}, 
       "data": "", 
       "files": {}, 
       "form": {
        "age": "22", 
        "name": "germey"
       }, 
        "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Connection": "close", 
        "Content-Length": "18", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.18.4"
      }, 
      "json": null, 
      "origin": "183.64.61.29", 
      "url": "http://httpbin.org/post"
    }
    

    响应

    response属性

    import requests
    response = requests.get('http://www.jianshu.com')
    print(type(response.status_code), response.status_code)
    print(type(response.headers), response.headers)
    print(type(response.cookies), response.cookies)
    print(type(response.url), response.url)
    print(type(response.history), response.history)
    return:
    <class 'int'> 200
    <class 'requests.structures.CaseInsensitiveDict'> {'Date': 'Thu, 01 Feb 2018 20:47:08 GMT', 'Server': 'Tengine', 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'ETag': 'W/"9f70e869e7cce214b6e9d90f4ceaa53d"', 'Cache-Control': 'max-age=0, private, must-revalidate', 'Set-Cookie': 'locale=zh-CN; path=/', 'X-Request-Id': '366f4cba-8414-4841-bfe2-792aeb8cf302', 'X-Runtime': '0.008350', 'Content-Encoding': 'gzip', 'X-Via': '1.1 gjf22:8 (Cdn Cache Server V2.0), 1.1 PSzqstdx2ps251:10 (Cdn Cache Server V2.0)', 'Connection': 'keep-alive'}
    <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie locale=zh-CN for www.jianshu.com/>]>
    <class 'str'> https://www.jianshu.com/
    <class 'list'> [<Response [301]>]
    
    状态码判断:常见的网页状态码:
    100: ('continue',),
    101: ('switching_protocols',),
    102: ('processing',),
    103: ('checkpoint',),
    122: ('uri_too_long', 'request_uri_too_long'),
        
    200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
    201: ('created',),
    202: ('accepted',),
    203: ('non_authoritative_info', 'non_authoritative_information'),
    204: ('no_content',),
    205: ('reset_content', 'reset'),
    206: ('partial_content', 'partial'),
    207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
    208: ('already_reported',),
    226: ('im_used',),
        
    # Redirection.
    300: ('multiple_choices',),
    301: ('moved_permanently', 'moved', '\o-'),
    302: ('found',),
    303: ('see_other', 'other'),
    304: ('not_modified',),
    305: ('use_proxy',),
    306: ('switch_proxy',),
    307: ('temporary_redirect', 'temporary_moved', 'temporary'),
    308: ('permanent_redirect','resume_incomplete', 'resume',), # These 2 to be removed in 3.0
        
    # Client Error.
    400: ('bad_request', 'bad'),
    401: ('unauthorized',),
    402: ('payment_required', 'payment'),
    403: ('forbidden',),
    404: ('not_found', '-o-'),
    405: ('method_not_allowed', 'not_allowed'),
    406: ('not_acceptable',),
    407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
    408: ('request_timeout', 'timeout'),
    409: ('conflict',),
    410: ('gone',),
    411: ('length_required',),
    412: ('precondition_failed', 'precondition'),
    413: ('request_entity_too_large',),
    414: ('request_uri_too_large',),
    415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
    416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
    417: ('expectation_failed',),
    418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
    421: ('misdirected_request',),
    422: ('unprocessable_entity', 'unprocessable'),
    423: ('locked',),
    424: ('failed_dependency', 'dependency'),
    425: ('unordered_collection', 'unordered'),
    426: ('upgrade_required', 'upgrade'),
    428: ('precondition_required', 'precondition'),
    429: ('too_many_requests', 'too_many'),
    431: ('header_fields_too_large', 'fields_too_large'),
    444: ('no_response', 'none'),
    449: ('retry_with', 'retry'),
    450: ('blocked_by_windows_parental_controls', 'parental_controls'),
    451: ('unavailable_for_legal_reasons', 'legal_reasons'),
    499: ('client_closed_request',),
        
    # Server Error.
    500: ('internal_server_error', 'server_error', '/o\', '✗'),
    501: ('not_implemented',),
    502: ('bad_gateway',),
    503: ('service_unavailable', 'unavailable'),
    504: ('gateway_timeout',),
    505: ('http_version_not_supported', 'http_version'),
    506: ('variant_also_negotiates',),
    507: ('insufficient_storage',),
    509: ('bandwidth_limit_exceeded', 'bandwidth'),
    510: ('not_extended',),
    511: ('network_authentication_required', 'network_auth', 'network_authentication'),
    

    高级操作

    文件上传

    使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理:

    实例:

    import requests
    
    files = {'file': open('cookie.txt', 'rb')}
    response = requests.post("http://httpbin.org/post", files=files)
    print(response.text)
    

    这是通过测试网站做的一个测试,返回值如下:

    {
    "args": {}, 
    "data": "", 
    "files": {
    "file": "#LWP-Cookies-2.0
    Set-Cookie3: BAIDUID="D2B4E137DE67E271D87F03A8A15DC459:FG=1"; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-02-13 11:15:12Z"; version=0
    Set-Cookie3: BIDUPSID=D2B4E137DE67E271D87F03A8A15DC459; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-02-13 11:15:12Z"; version=0
    Set-Cookie3: H_PS_PSSID=25641_1465_21087_17001_22159; path="/"; domain=".baidu.com"; path_spec; domain_dot; discard; version=0
    Set-Cookie3: PSTM=1516953672; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-02-13 11:15:12Z"; version=0
    Set-Cookie3: BDSVRTM=0; path="/"; domain="www.baidu.com"; path_spec; discard; version=0
    Set-Cookie3: BD_HOME=0; path="/"; domain="www.baidu.com"; path_spec; discard; version=0
    "
    }, 
    "form": {}, 
    "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "909", 
    "Content-Type": "multipart/form-data; boundary=84835f570cfa44da8f4a062b097cad49", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
    }, 
    "json": null, 
    "origin": "183.64.61.29", 
    "url": "http://httpbin.org/post"
    }
    

    获取cookie

    当需要cookie时,直接调用response.cookieimgresponse为请求后的返回值)

    import requests
    
    response = requests.get("https://www.baidu.com")
    print(response.cookies)
    for key, value in response.cookies.items():
    print(key + '=' + value)
    

    输出结果:

    <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
    BDORZ=27315
    

    会话维持、模拟登陆

    如果某个响应中包含一些Cookie,你可以快速访问它们:

    import requests
    
    r = requests.get('http://www.google.com.hk/')
    print(r.cookies['NID'])
    print(tuple(r.cookies))
    

    要想发送你的cookies到服务器,可以使用 cookies 参数:

    import requests
    
    url = 'http://httpbin.org/cookies'
    cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
    

    # 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等
    特殊符号都不能作为Cookie的内容。

    r = requests.get(url, cookies=cookies)
    print(r.json())
    

    证书验证(SSL Cert Verification)

    #证书验证(大部分网站都是https)
    import requests
    respone=requests.get('https://www.12306.cn') #如果是ssl请求,首先检查证书是否合法,不合法则报错,程序终端
    
    
    #改进1:去掉报错,但是会报警告
    import requests
    respone=requests.get('https://www.12306.cn',verify=False) #不验证证书,报警告,返回200
    print(respone.status_code)
    
    
    #改进2:去掉报错,并且去掉警报信息
    import requests
    from requests.packages import urllib3
    urllib3.disable_warnings() #关闭警告
    respone=requests.get('https://www.12306.cn',verify=False)
    print(respone.status_code)
    
    #改进3:加上证书
    #很多网站都是https,但是不用证书也可以访问,大多数情况都是可以携带也可以不携带证书
    #知乎百度等都是可带可不带
    #有硬性要求的,则必须带,比如对于定向的用户,拿到证书后才有权限访问某个特定网站
    import requests
    respone=requests.get('https://www.12306.cn',
                         cert=('/path/server.crt',
                               '/path/key'))
    print(respone.status_code)
    

    认证设置

    #官网链接:http://docs.python-requests.org/en/master/user/authentication/
    
    #认证设置:登陆网站是,弹出一个框,要求你输入用户名密码(与alter很类似),此时是无法获取html的
    # 但本质原理是拼接成请求头发送
    #         r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
    # 一般的网站都不用默认的加密方式,都是自己写
    # 那么我们就需要按照网站的加密方式,自己写一个类似于_basic_auth_str的方法
    # 得到加密字符串后添加到请求头
    #         r.headers['Authorization'] =func('.....')
    
    #看一看默认的加密方式吧,通常网站都不会用默认的加密设置
    import requests
    from requests.auth import HTTPBasicAuth
    r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
    print(r.status_code)
    
    #HTTPBasicAuth可以简写为如下格式
    import requests
    r=requests.get('xxx',auth=('user','password'))
    print(r.status_code)
    

    代理设置

    在进行爬虫爬取时,有时候爬虫会被服务器给屏蔽掉,这时采用的方法主要有降低访问时间,通过代理ip访问,
    如下:

    import requests
    
    proxies = {
    "http": "http://127.0.0.1:9743",
    "https": "https://127.0.0.1:9743",
    }
    
    
    response = requests.get("https://www.taobao.com", proxies=proxies)
    print(response.status_code)
    

    ip可以从网上抓取,或者某宝购买

    如果代理需要设置账户名和密码,只需要将字典更改为如下:

    proxies = {
    "http":"http://user:password@127.0.0.1:9999"
    }
    

    如果你的代理是通过sokces这种方式则需要

    pip install "requests[socks]"
    proxies= {
    "http":"socks5://127.0.0.1:9999",
    "https":"sockes5://127.0.0.1:8888"
    }
    

    超时设置

    访问有些网站时可能会超时,这时设置好timeout就可以解决这个问题

    import requests
    from requests.exceptions import ReadTimeout
    try:
    response = requests.get("http://httpbin.org/get", timeout = 0.5)
    print(response.status_code)
    except ReadTimeout:
    print('Timeout')
    

    正常访问,状态吗返回200

    认证设置

    如果碰到需要认证的网站可以通过requests.auth模块实现

    import requests
    
    from requests.auth import HTTPBasicAuth
    
    response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
    print(response.status_code)
    

    当然这里还有一种方式

    import requests
    
    response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
    print(response.status_code)
    

    异常处理

    遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError 异常。

    遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

    若请求超时,则抛出一个 Timeout 异常。

    若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

    所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

    上传文件

    import requests
    files={'file':open('a.jpg','rb')}
    respone=requests.post('http://httpbin.org/post',files=files)
    print(respone.status_code)
    

    带参数的GET请求->headers

    通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下

    Host
    Referer #大型网站通常都会根据该参数判断请求的来源
    User-Agent #客户端
    Cookie #Cookie信息虽然包含在请求头里,但requests模块有单独的参数来处理他,headers={}内就不要放它了
    

    添加headers(浏览器会识别请求头,不加可能会被拒绝访问,比如访问https://www.zhihu.com/explore)

    import requests
    response=requests.get('https://www.zhihu.com/explore')
    response.status_code #500
    
    
    #自己定制headers
    headers={
        'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36',
    
    }
    respone=requests.get('https://www.zhihu.com/explore',
                         headers=headers)
    print(respone.status_code) #200
    

    带参数的GET请求->cookies

    import requests
    
    Cookies={   'user_session':'rzNme4L6LTH7QSresq8w0BVYhTNt5GS-asNnkOe7_FZ2CjB6',
    }
    
    response=requests.get('https://github.com/settings/emails',
                 cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制
    
    
    print('306334678@qq.com' in response.text) #True
    

    发送post请求,模拟浏览器的登录行为

    对于登录来说,应该输错用户名或密码然后分析抓包流程,用脑子想一想,输对了浏览器就跳转了,还分析个毛线,累死你也找不到包

    自动登录gitbub(自己处理cookies))

    '''
    一 目标站点分析
        浏览器输入https://github.com/login
        然后输入错误的账号密码,抓包
        发现登录行为是post提交到:https://github.com/session
        而且请求头包含cookie
        而且请求体包含:
            commit:Sign in
            utf8:✓
            authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
            login:egonlin
            password:123
    
    
    二 流程分析
        先GET:https://github.com/login拿到初始cookie与authenticity_token
        返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
        最后拿到登录cookie
    
        ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
    '''
    
    import requests
    import re
    
    #第一次请求
    r1=requests.get('https://github.com/login')
    r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授权)
    authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN
    
    #第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
    data={
        'commit':'Sign in',
        'utf8':'✓',
        'authenticity_token':authenticity_token,
        'login':'317828332@qq.com',
        'password':'alex3714'
    }
    r2=requests.post('https://github.com/session',
                 data=data,
                 cookies=r1_cookie
                 )
    
    
    login_cookie=r2.cookies.get_dict()
    
    
    #第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置
    r3=requests.get('https://github.com/settings/emails',
                    cookies=login_cookie)
    
    print('317828332@qq.com' in r3.text) #True
    

    requests.session()自动帮我们保存cookie信息

    import requests
    import re
    
    session=requests.session()
    #第一次请求
    r1=session.get('https://github.com/login')
    authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN
    
    #第二次请求
    data={
        'commit':'Sign in',
        'utf8':'✓',
        'authenticity_token':authenticity_token,
        'login':'317828332@qq.com',
        'password':'alex3714'
    }
    r2=session.post('https://github.com/session',
                 data=data,
                 )
    
    #第三次请求
    r3=session.get('https://github.com/settings/emails')
    
    print('317828332@qq.com' in r3.text) #True
    

    补充json

    json的用法

    requests.post(url='xxxxxxxx',
                  data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed
    
    #如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值
    requests.post(url='',
                  data={'':1,},
                  headers={
                      'content-type':'application/json'
                  })
    
    
    requests.post(url='',
                  json={'':1,},
                  ) #默认的请求头:application/json
    
    json的用法
    
  • 相关阅读:
    20201304杨淑钰+快速浏览教材
    20201304 自我介绍
    熟悉编程语言
    俄罗斯方块游戏代码的改写
    2020 -2021-1 20201319 《信息安全专业导论》第八周学习总结
    如何学好编程
    2020-2021-1 20201319 《信息安全专业导论》第七周学习总结
    2020-2021-1 20201319 《信息安全专业导论》第六周学习总结
    实现进制转换伪代码
    斐波那契数列递归实现
  • 原文地址:https://www.cnblogs.com/jie9527-/p/11935026.html
Copyright © 2020-2023  润新知