#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'模式。