requests发送http请求相关

本文介绍了如何使用requests库在Python中发送HTTP请求,包括基本的GET和POST操作,以及处理响应内容和重定向的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 发送请求相关
    import requests
    
    # 发送get请求
    url = 'http://example.com'
    
    resp = requests.get(url)
    
    resp = requests.post(url, data={'key': 'value'})
    
    resp = requests.put(url, data={'key': 'value'})
    
    resp = requests.delete(url)
    
    resp = requests.head(url)
    
    resp = requests.options(url)
    
    """ 请求时相应的参数的含义以及返回值
        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary, list of tuples or bytes to send
                     in the query string for the :class:`Request`.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
                      object to send in the body of the :class:`Request`.
        :param json: (optional) A JSON serializable Python object to send in the body of the 
                      :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the 
                      :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the 
                      :class:`Request`.
        :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': 
                       file-tuple}``) for multipart encoding upload.
                       ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ` 
                       `('filename', fileobj, 'content_type')``
                       or a 4-tuple ``('filename', fileobj, 'content_type', 
                       custom_headers)``, where ``'content-type'`` is a string
                       defining the content type of the given file and ``custom_headers`` a 
                       dict-like object containing additional headers to add for the file.
        :param auth:   (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How many seconds to wait for the server to send data
                        before giving up, as a float, or a :ref:`(connect timeout, read
                        timeout) <timeouts>` tuple. 
                        :type timeout: float or tuple
        :param allow_redirects: (optional) Boolean. Enable/disable                                     
                                GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults 
                                to ``True``.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
        :param verify: (optional) Either a boolean, in which case it controls whether we 
                       verify the server's TLS certificate, or a string, in which case it 
                       must be a path to a CA bundle to use. Defaults to ``True``.
        :param stream: (optional) if ``False``, the response content will be immediately 
                       downloaded.
        :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, 
                     ('cert', 'key') pair.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
    """
    
    
    
    

     

  2. 获取相应内容相关
    import requests
    
    url = 'http://example.com'
    
    resp = requests.get(url)
    
    # 响应内容
    
    # 获取响应文本
    resp.text
    
    # 获取二进制响应内容
    resp.content # 配合文件读写可以爬取图片
    
    # Json响应内容,要求响应的字符串为Json格式的字符串
    result = resp.json()
    
    # 原始响应内容
    resp = requests.get(url, stream=True)
    resp.raw
    resp.raw.read(10)
    # 将文本流保存至文件中:
    with open(filename, 'wb') as f:
        for chunk in resp.iter_content(chunk_size):
            f.write(chunk)
    # 使用 Response.iter_content 将会处理大量你直接使用 Response.raw 不得不处理的。 当流下载时,上# 面是优先推荐的获取内容方式。
    
    # 响应状态码
    resp.status_code
    
    # 响应头
    resp.headers['Content-Type']
    resp.headers.get('content-type')

     

  3. 重定向
    import requests
    # 在默认情况下,除了HEAD,Requests会自动处理所有的重定向
    # 可以使用响应对象的history方法追踪重定向
    
    url = 'http://example.com'
    # 查看重定向
    resp = requests.get(url)
    resp.status_code    # 一般为200 
    resp.history    # 结果类似于[<Response [301]>]
    
    # 如果不希望使用重定向
    resp = requests.get(url, allow_redirects=False)
    resp.status_code    # 301
    resp.history    # []

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值