|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import urllib.request
import chardet
f=open('urls.txt','w+')
f.writelines(['http://www.fishc.com\n','http://www.baidu.com\n',
'http://www.taobao.com\n','http://www.zhihu.com\n'])
f.close()
with open('urls.txt','r+') as f:
count=0
for each in f:
each=each.strip()
response=urllib.request.urlopen(each)
content_bytes=response.read()
if chardet.detect(content_bytes)['encoding']=='gb2312' or chardet.detect(content_bytes)['encoding']=='gbk':
encode_type='gbk'
else:
dict=chardet.detect(content_bytes)
encode_type=dict['encoding']
print(encode_type)
with open(f'url{count}.txt','w+',encoding=encode_type) as file: #为什么这里去掉encoding程序就会在爬取淘宝页面源码的时候报错啊???
file.write(content_bytes.decode(encode_type))
count+=1
这样程序没问题
但是去掉encoding再去爬取,前两个是正常的,但是在爬取淘宝的时候报错:'gbk' codec can't encode character '\ue603' in position 25668: illegal multibyte sequence
这是为什么?这不是打开文件吗?我是要往里面写东西,为啥open的这个参数会影响到我的程序结果? |
|