python urllib request urlopen请求网页返回bytes类型

发布于 2022-09-07 19:31:45 字数 452 浏览 11 评论 0

我在学习urllib这个库,使用以下代码请求面度的主页,返回的结果为<class 'bytes'>,我尝试了多种方法进行解码,均不成功(报错或为空)
以下为代码:

from urllib import request
f = request.urlopen('http://www.baidu.com/')
print(f.read())
print(type(f.read()))
x = f.read()
print(x.decode(encoding='utf-8'))

以下为输出:
……n</body>n</html>nrnrnrnnrn'
<class 'bytes'>
''
请大佬指点,谢谢!
图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

百思不得你姐 2022-09-14 19:31:45

首次调用read()时有返回,之后的调用一直返回b''

>>> f = request.urlopen('http://www.baidu.com/')
>>> f.read()
b'<!DOCTYPE html>\n<!--STATUS OK-->\n\r...(略)...'
>>> f.read()
b''

因此,从你的第二个f.read()开始,都是返回b''了。
这样代码在我这能正确获取网页并解码:

from urllib import request
f = request.urlopen('http://www.baidu.com/')
x = f.read()
print(x.decode(encoding='utf-8'))

http.client.HTTPResponse.read是这样定义的:

def read(self, amt=None):
    if self.fp is None:
        return b""

    if self._method == "HEAD":
        self._close_conn()
        return b""

    if amt is not None:
        # Amount is given, implement using readinto
        b = bytearray(amt)
        n = self.readinto(b)
        return memoryview(b)[:n].tobytes()
    else:
        # Amount is not given (unbounded read) so we must check self.length
        # and self.chunked

        if self.chunked:
            return self._readall_chunked()
...(略)...

第一次read()时,在self._readall_chunked()self.fp被置为None,并关闭了self.fp
因此再次调用read()时,直接返回了b''

北渚 2022-09-14 19:31:45

不建议使用 urllib 库,推荐 requests 库

import requests
response = requests.get('https://www.baidu.com/')
response.encoding = 'utf-8'
print(response.text)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文