【问题标题】:How to get string formate from response of HTTP GET in Python? [duplicate]如何从 Python 中的 HTTP GET 响应中获取字符串格式? [复制]
【发布时间】:2018-11-05 21:29:35
【问题描述】:

我有以下任务

编写一个名为“get_response”的函数,其中三个字符串参数依次表示协议、服务器名称和 HTTP GET 请求的路径。将 HTTPS GET 请求的响应返回到由这些输入形成的 url。响应应以字符串形式返回

我写了以下代码。

def get_response(protocol, server, path):
str = protocol + "://" + server + "/" + path
contents = urllib.request.urlopen(str).read()

return contents

我在运行代码时得到以下信息

b'小学生'

问题想要的是字符串格式,并且答案中只有“学生”。我尝试将其转换为 str,但它不起作用。

有什么建议吗?

【问题讨论】:

    标签: python http get


    【解决方案1】:

    使用解码

    import urllib.request
    
    
    def get_response(protocol, server, path):
        str = protocol + "://" + server + "/" + path
        contents = urllib.request.urlopen(str).read()
    
        return contents.decode("utf-8")
    

    【讨论】:

    • 忽略缩进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    相关资源
    最近更新 更多