文本
#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
网友评论