zoukankan      html  css  js  c++  java
  • python保存图片

    #coding=utf-8
    
    import requests
    
    url ="https://images.pexels.com/photos/1181767/pexels-photo-1181767.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
    
    headers = {
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36",
        "referer":"https://www.pexels.com/zh-cn/photo/4k-1484728/"
    }
    
    response = requests.get(url,headers=headers)
    print(response.status_code)
    
    with open("a.jpg","wb") as f:
        f.write(response.content)
        f.close()

    ython2随机写入二进制文件:

    with open('/python2/random.bin','w') as f:
    f.write(os.urandom(10))
    但使用Python3会报错:

    TypeError:must be str, not bytes
    原因为:Python3给open函数添加了名为encoding的新参数,而这个新参数的默认值却是‘utf-8’。这样在文件句柄上进行read和write操作时,系统就要求开发者必须传入包含Unicode字符的实例,而不接受包含二进制数据的bytes实例。

    解决方法:

    使用二进制写入模式(‘wb’)来开启待操作文件,而不能像原来那样,采用字符写入模式(‘w’)。

    同时适配Python3和Python2的方法:

    with open('python3/rndom.bin','wb') as f:
    f.write(os.urandom(10))
    文件读取数据的时候也有类似的问题。解决这种问题的办法也相似:用'rb'模式(二进制模式)打开文件,而不要使用'r'模式。

  • 相关阅读:
    JS定时执行,循环执行
    Ecshop(二次开发)
    百度歌曲接口
    给大家讲讲在哪些地方发外链最好
    360浏览器默认以兼容模式或急速模式方式打开页面
    子iframe 怎么调用 父级的JS函数
    ASP 发送邮件
    PHP发送邮件
    php表单数据验证类
    js获取url传递参数
  • 原文地址:https://www.cnblogs.com/php-linux/p/12434030.html
Copyright © 2011-2022 走看看