python 学习笔记-requests

开始学习python 语言,从网上爬取数据并保存,发现直接下边代码不行

import requests

r = requests.get('https://book.douban.com/')
print(r.status_code)
print(r.headers)
print(r.encoding)
r.encoding='utf-8'
print(r.apparent_encoding)
#print(r.text)
#print(r.cookie)
print(r.url)
#d = requests.delete('https://book.douban.com/')

file = open('sampleList.txt', 'w')
file.write(r.text)
file.close()

在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,出现上述问题。 解决的办法就是,改变目标文件的编码:

更改命令如下,添加编码方式utf-8

file = open('sampleList.txt','w',encoding=utf-8)


猜你喜欢

转载自blog.csdn.net/gzh9255/article/details/81029427