我有一些代码读取 URL 并写入磁盘。这里是 -
url = 'http://www.cs.purdue.edu/homes/ninghui/courses/Spring06/lectures/lecture05.pdf'
ret = requests.get(url)
print ret.headers
print ret.headers['content-encoding']
print ret.headers['content-type']
pathToWrite = 'tmp/test.pdf'
try:
fd = os.open(pathToWrite, os.O_RDWR | os.O_CREAT)
try:
os.write(fd, ret.text)
except Exception as e:
print 'cannot write to file ' + pathToWrite
raise
try:
os.close(fd)
except:
print 'cannot close file ' + pathToWrite
raise
except:
print 'file cannot be opened ' + pathToWrite
raise
使用上面的代码,我可以获取pdf文件并将其写入磁盘,但出现以下错误-
UnicodeEncodeError: 'charmap' codec can't encode characters in position 12-13: character maps to <undefined>
当我使用以下 API 时,我得到了同样的错误 -
f = open(pathTowWrite, 'wb')
f.write(ret.text)
我觉得我错过了一些明显的东西。这似乎太简单了,不会出错。