鱼C论坛

 找回密码
 立即注册
查看: 2782|回复: 2

python爬虫初学者求助

[复制链接]
发表于 2016-6-16 20:51:31 | 显示全部楼层 |阅读模式
5鱼币
本帖最后由 776667 于 2016-6-16 20:53 编辑
  1. import urllib.request
  2. import chardet

  3. def url_download():
  4.     response = urllib.request.urlopen('http://www.fishc.com').read()
  5.     with open('.\\url_1.txt','x') as record:
  6.         print(response.decode(chardet.detect(response)['encoding']))
  7.         record.write(response.decode(chardet.detect(response)['encoding']))

  8. if __name__ == '__main__':
  9.     url_download()
复制代码


运行上面这段程序后打印内容正常,但是执行到record.write(response.decode(chardet.detect(response)['encoding']))的时候丢出了错误:

UnicodeEncodeError: 'gbk' codec can't encode character '\u013d' in position 135: illegal multibyte sequence

请问巨巨们这是为啥,response被decode以后确定为str类型,为啥写入文本的时候会丢出UnicodeEncodeError


最佳答案

查看完整内容

在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,出现上述问题。(文字来源于网络) import urllib.request import chardet def url_download(): response = urllib.request.urlopen('http://www.fishc.com').read() with open('.\%url_1.txt','x', encoding='utf-8') as record: ...
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-6-16 20:51:32 | 显示全部楼层
在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析我们的网络数据流txt,然而txt此时已经是decode过的unicode编码,这样的话就会导致解析不了,出现上述问题。(文字来源于网络)


import urllib.request
import chardet

def url_download():
    response = urllib.request.urlopen('http://www.fishc.com').read()
    with open('.\\url_1.txt','x', encoding='utf-8') as record:
        print(response.decode(chardet.detect(response)['encoding']))
        record.write(response.decode(chardet.detect(response)['encoding']))

if __name__ == '__main__':
    url_download()
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-6-17 18:16:33 | 显示全部楼层
啊,明白了,确实忽略了这问题。。感谢
改成
with open('.\\url_1.txt','x', encoding=chardet.detect(response)['encoding']) as record:
应该就没问题了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-21 09:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表