【Python】requests的response.text 和 urllib.request 的 response.read()的区别

刚写代码的时候,我经常会把requests 和 urllib下的request 包搞混,这两个请求响应的方法看起来很相似,但是写获取的方法是不一样的。

前者requests 是用response.text 来获取源码,而 urllib.request是用 response.read() 来获取html内容的,他们返回的响应内容也不一样,获取响应的状态码也会不一样。

如果搞混读取的方法,可能就会出现:【‘Response’ object has no attribute ‘read’】的问题:
在这里插入图片描述或者状态值获取不对时出现【‘Response’ object has no attribute ‘status’】的问题:在这里插入图片描述

具体的区别:

1. response.text

在Python的requests库中,它的使用示例如下:

# 使用response.text读取文本内容
import requests

# 发送GET请求
response = requests.get('https://example.com')

text_content = response.text
print('获取响应状态:',response.status_code)
print(type(text_content)) #str
print(text_content)

#==============结果:==================================
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

requests库的response.text的特点:

  • 返回内容:返回的是解码后的【Unicode字符串】,str
  • 解码方法:它自动解码响应体,通常是使用响应头中的Content-Type和charset参数,自动选择合适的编码来解码响应内容。
  • 适用场景:这个方法通常用于读取文本内容,如HTML、JSON或XML。

2. response.read()

urllib.request模块的response.read()的特点:

  • 返回内容:返回响应体的【原始字节串】, bytes。
  • 解码方法:不进行任何解码,直接返回二进制数据。
  • 适用场景:它常用于读取非文本内容,如图片、视频或二进制文件。

它的使用示例如下:

# 使用response.read()读取原始字节数据
from urllib.request import urlopen

response=urlopen('https://example.com')
print('获取响应状态:',response.status)
binary_content = response.read()
print(type(binary_content)) #<class 'bytes'>
print(binary_content)
#==============结果:==================================
b'<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset="utf-8" />\n    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n    <meta name="viewport" content="width=device-width, initial-scale=1" />\n    <style type="text/css">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 2em;\n        background-color: #fdfdff;\n        border-radius: 0.5em;\n        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        div {\n            margin: 0 auto;\n            width: auto;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is for use in illustrative examples in documents. You may use this\n    domain in literature without prior coordination or asking for permission.</p>\n    <p><a href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'

3.主要区别

  1. 解码:requests的response.text自动解码,而urllib.request的response.read()返回原始字节数据。

  2. 获取响应状态的方式:requests的是用status_code,而urllib.request的是status

  3. 易用性:requests提供了更高级的接口和更多的便利功能,如会话管理、Cookie持久化等; 而urllib.request提供了更多的控制和灵活性,但使用起来可能更复杂。

  4. 库的依赖:requests不是Python标准库的一部分,需要单独安装,通常被认为是更高级、更易用的HTTP库;而urllib.request是Python标准库的一部分,无需额外安装。

  5. 处理结果上:response.text可以直接对返回的字符串进行操作,比如解析JSON或HTML;
    而使用response.read()时,可能需要先将二进制数据转换为适当的格式,比如使用BytesIO来处理二进制数据,或者将其解码为字符串才能使用!

总之,我们在使用的过程中,大家要注意两者不要搞混了哈~

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的urllibrequests是两个常用的网络请求库。urllibPython标准库中的模块,提供了一些用于进行网络请求的函数和类,使用简单但功能相对较少。而requests是一个第三方库,功能更丰富,提供了更方便的API来发送HTTP请求和处理响应。 在使用urllib进行GET请求时,可以使用urlopen方法来发送请求并获取响应,通过调用read方法来读取响应数据,然后使用decode方法进行解码。以下是一个示例: import urllib.request response = urllib.request.urlopen('http://www.baidu.com') print(response.read().decode()) 而对于POST请求,urllib并没有单独提供相应的函数,而是通过构建Request对象来传递data参数来实现。具体的示例代码如下: import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python'} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read() 另外,requests库提供了更加方便的API来发送GET和POST请求,并处理HTTP响应。以下是一个使用requests库的示例代码: import requests resp = requests.get('http://www.baidu.com') print(resp.text) 可以看到,requests的使用更加简洁明了,通过调用get方法来发送GET请求并获取响应,然后通过text属性来获取响应内容。 综上所述,urllibrequests都是常用的Python网络请求库,根据需求选择适合的库来进行网络请求操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python 网络请求模块 urllibrequests](https://blog.csdn.net/aifeier1982/article/details/101950448)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值