文件写入

文本
#urlopen
import urllib.request
url = "http://yun.itheima.com"

response = urllib.request.urlopen(url)

res = response.read().decode("utf-8")
# 源代码
with open("黑马.txt","w") as f:
    f.write(res)
    f.close()
print(res)
#Request
import requests

url = "https://www.jianshu.com/p/f7216fe6da82"
response = requests.get(url)
print(response.text)

with open('xx.txt',"w") as f:
    f.write(response.text)
    # 如果报错gbk  ===> f.write(response.res.decode("utf-8"))也可以直接response.encoding = "utf-8"
    f.close()

#区别,response.read().decode("utf-8")====>response.text ,requests自动转转码


###图片等二进制

urlopen--用 urlretrieve

import urllib.request

url = "http://img0.bdstatic.com/static/searchresult/img/logo-2X_b99594a.png"

res = urllib.request.urlretrieve(url,"write/百度3.png")

print(res)      #<class 'tuple'>
# with open("write/百度1.png","wb") as f:
#   f.write(res.read)#此处报错
#   f.close

requests

import requests
url = "http://img0.bdstatic.com/static/searchresult/img/logo-2X_b99594a.png"

# res = urllib.request.Request(url)
# response = urllib.request.urlopen(res)
res = requests.get(url)
print(type(res.content))            # <class 'bytes'>
with open("write/百度4.png","wb") as f:
    f.write(res.content)
    f.close
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容