python url请求响应解码

python url request response decoding

我正在尝试从 urllib.request 响应中获取 link 图像。

我正在尝试从此页面获取内容:https://drscdn.500px.org/photo/27428737/m%3D900/v2?webp=true&sig=3d3700c82ea515ecc0b66ca265d6909d67861fbe055c0e817b535f75b21c7ebf 并对其进行解码,但 decode("utf-8") 方法给出了错误:'utf-8' codec can't decode byte位置 0 中的 0xff:无效的起始字节。我已经在浏览器控制台中使用 document.characterSet 检查了页面编码,它与 utf-8 编码匹配。

def ex4():
    url = sys.argv[1]
    r = re.compile(b"<img .*? src=\"([^\"])*\" (.*?)*>")
    try:
        resource = urllib.request.urlopen(url)
        response = resource.read().decode("utf-8")
        print(response)
        obj = r.search(response)
        if obj:
            print(obj.group(1))
        else:
            print("not found")
    except Exception as e:
        print("error: ", e)


ex4()

为您提供二值图像,因此您可以直接保存或处理图像。
例如:

url = 'https://drscdn.500px.org/photo/27428737/m%3D900/v2?webp=true&sig=3d3700c82ea515ecc0b66ca265d6909d67861fbe055c0e817b535f75b21c7ebf'
resource = urllib.request.urlopen(url)
response = resource.read()

with open('/tmp/foo.jpg', 'wb') as f:
    f.write(response)

你想达到什么目的?获取图像并将其保存到文件?如果是,请将其保存在文件中

def ex4():
    url = sys.argv[1]
    try:
        resource = urllib.request.urlopen(url)
        response = resource.read()
        with open('img.png', 'wb') as f:
            f.write(a)
    except Exception as e:
        print("error: ", e)

ex4()