📜  Python请求教程

📅  最后修改于: 2022-05-13 01:55:31.233000             🧑  作者: Mango

Python请求教程

Requests 库是Python的组成部分之一,用于向指定的 URL 发出 HTTP 请求。无论是 REST API 还是 Web 抓取,都必须学习请求以进一步使用这些技术。当向 URI 发出请求时,它会返回响应。 Python requests 提供了用于管理请求和响应的内置功能。

python-请求-模块

为什么要学习Python请求模块?

  • Requests 是一个 Apache2 许可的 HTTP 库,允许使用Python发送 HTTP/1.1 请求。
  • 要玩网络, Python请求是必须的。无论是访问 API、下载整个 Facebook 页面,还是更酷的东西,都必须向 URL 发出请求。
  • 请求扮演的主要角色是处理 REST API 和 Web Scrapping。
  • 使用请求和 Web 抓取检查示例Python脚本 – 使用 BeautifulSoup 在Python中实现 Web 抓取
    最近关于请求的文章!

    安装请求

    请求安装取决于 eis 使用的操作系统类型,任何地方的基本命令都是打开命令终端并运行,

    pip install requests

    在任何操作系统上安装请求的基本方法是获取基本文件并手动安装请求,请求在 GitHub 上积极开发,代码始终可用。对于代码 - 访问这里。
    您可以克隆公共存储库:

    git clone git://github.com/psf/requests.git

    一旦你有了源代码的副本,你可以将它嵌入到你自己的Python包中,或者轻松地将它安装到你的站点包中:

    cd requests
    pip install .

    更多结帐 – 如何在Python中安装请求 – 适用于 windows、linux、mac

    发出请求

    Python requests 模块有几个内置方法可以使用 GET、POST、PUT、PATCH 或 HEAD 请求向指定的 URI 发出 Http 请求。 Http 请求旨在从指定的 URI 检索数据或将数据推送到服务器。它作为客户端和服务器之间的请求-响应协议工作。让我们演示如何向端点发出 GET 请求。
    GET 方法用于使用给定的 URI 从给定的服务器检索信息。 GET 方法发送附加到页面请求的编码用户信息。页面和编码信息用“?”分隔字符。
    例如:

    https://www.google.com/search?q=hello
    如何通过Python Requests 发出 GET 请求

    Python 的 requests 模块提供了名为get()的内置方法,用于向指定的 URI 发出 GET 请求。

    句法 -

    requests.get(url, params={key: value}, args)
    

    例子 -

    出于示例目的,让我们尝试向 github 的 API 发出请求。

    import requests
       
    # Making a GET request
    r = requests.get('https://api.github.com/users/naveenkrnl')
      
    # check status code for response received
    # success code - 200
    print(r)
      
    # print content of request
    print(r.content)
    

    将此文件保存为 request.py 并通过终端运行,

    python request.py

    输出 -
    python请求获取方法

    更多信息,请访问 GET 方法 – Python请求

    Http 请求方法 –

    MethodDescription
    GETGET method is used to retrieve information from the given server using a given URI.
    POSTPOST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it
    PUTThe PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.
    DELETEThe DELETE method deletes the specified resource
    HEADThe HEAD method asks for a response identical to that of a GET request, but without the response body.
    PATCHIt is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource

    响应对象

    当向 URI 发出请求时,它会返回响应。就Python而言,这个 Response 对象由 requests.method() 返回,方法是 get、post、put 等。Response 是一个强大的对象,具有许多有助于规范化数据或创建理想代码部分的函数和属性。例如, response.status_code从 headers 本身返回状态代码,可以检查请求是否成功处理。
    响应对象可用于暗示许多特性、方法和功能。

    例子 :
    # import requests module
    import requests
      
    # Making a get request
    response = requests.get('https://api.github.com/')
      
    # print request object
    print(response.url)
      
    # print status code
    print(response.status_code)
    

    将此文件保存为 request.py,并使用以下命令运行

    Python request.py

    响应-python-请求
    状态码 200 表示请求成功。

    应对方法

    MethodDescription
    response.headersresponse.headers returns a dictionary of response headers.
    response.encodingresponse.encoding returns the encoding used to decode response.content.
    response.elapsedresponse.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response.
    response.close()response.close() closes the connection to the server.
    response.contentresponse.content returns the content of the response, in bytes.
    response.cookiesresponse.cookies returns a CookieJar object with the cookies sent back from the server.
    response.historyresponse.history returns a list of response objects holding the history of request (url).
    response.is_permanent_redirectresponse.is_permanent_redirect returns True if the response is the permanent redirected url, otherwise False.
    response.is_redirectresponse.is_redirect returns True if the response was redirected, otherwise False.
    response.iter_content()response.iter_content() iterates over the response.content.
    response.json()response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
    response.urlresponse.url returns the URL of the response.
    response.textresponse.text returns the content of the response, in unicode.
    response.status_coderesponse.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).
    response.requestresponse.request returns the request object that requested this response.
    response.reasonresponse.reason returns a text corresponding to the status code.
    response.raise_for_status()response.raise_for_status() returns an HTTPError object if an error has occurred during the process.
    response.okresponse.ok returns True if status_code is less than 200, otherwise False.
    response.linksresponse.links returns the header links.

    使用Python请求进行身份验证

    身份验证是指授予用户访问特定资源的权限。由于不能允许每个人访问每个 URL 的数据,因此主要需要身份验证。为了实现这种身份验证,通常通过 Authorization 标头或服务器定义的自定义标头提供身份验证数据。

    例子 -

    # import requests module
    import requests
    from requests.auth import HTTPBasicAuth
      
    # Making a get request
    response = requests.get('https://api.github.com / user, ',
                auth = HTTPBasicAuth('user', 'pass'))
      
    # print request object
    print(response)
    

    将“user”和“pass”替换为您的用户名和密码。它将验证请求并返回响应 200,否则将返回错误 403。
    验证-python-请求
    更多访问 – 使用Python请求进行身份验证

    SSL 证书验证

    Requests 为 HTTPS 请求验证 SSL 证书,就像 Web 浏览器一样。 SSL 证书是以数字方式将加密密钥绑定到组织详细信息的小型数据文件。通常,具有 SSL 证书的网站被称为安全网站。默认情况下,启用 SSL 验证,如果无法验证证书,Requests 将抛出 SSLError。

    禁用 SSL 证书验证

    让我们尝试使用Python请求访问具有无效 SSL 证书的网站

    # import requests module
    import requests
      
    # Making a get request
    response = requests.get('https://expired.badssl.com/')
      
    # print request object
    print(response)
    

    输出 :-
    ssl-证书验证-python-requests
    该网站没有设置 SSL,因此会引发此错误。
    也可以仅通过Python请求将链接传递给证书以进行验证。

    # import requests module
    import requests
      
    # Making a get request
    response = requests.get('https://github.com', verify ='/path/to/certfile')
      
    # print request object
    print(response)
    

    如果提供的路径对于 github.com 的 SSL 证书是正确的,这将起作用。
    欲了解更多信息,请访问 SSL 证书验证 – Python请求

    会话对象

    会话对象允许跨请求保留某些参数。它还在从 Session 实例发出的所有请求中保留 cookie,并将使用 urllib3 的连接池。因此,如果对同一主机发出多个请求,则底层 TCP 连接将被重用,这可能会导致性能显着提高。一个会话对象请求的所有方法。

    使用会话对象

    让我们通过将 cookie 设置为 url 然后再次发出请求来检查是否设置了 cookie 来说明会话对象的使用。

    # import requests module
    import requests
      
    # create a session object
    s = requests.Session()
      
    # make a get request
    s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
      
    # again make a get request
    r = s.get('https://httpbin.org/cookies')
      
    # check if cookie is still set
    print(r.text)
    


    输出:

    会话对象-python-请求
    有关更多信息,请访问 – 会话对象 – Python请求