python - 爬虫内容保存成文本文件 编码问题
问题描述
测试一个非常简单的爬虫,把一个非常简约风格的网页的文本内容保存到本地的电脑上。最后出现错误:
UnicodeEncodeErrorTraceback (most recent call last)<ipython-input-35-ead5570b2e15> in <module>() 7 filename=str(i)+’.txt’ 8 with open(filename,’w’)as f:----> 9 f.write(content) 10 print(’当前小说第{}章已经下载完成’.format(i)) 11 f.close()UnicodeEncodeError: ’gbk’ codec can’t encode character ’xa0’ in position 7: illegal multibyte sequence
代码如下:
In [1]: import requestsIn [2]: from bs4 import BeautifulSoupIn [3]: re=requests.get(’http://www.qu.la/book/168/’)In [4]: html=re.textIn [5]: soup=BeautifulSoup(html,’html.parser’)In [6]: list=soup.find(id='list')In [9]: link_list=list.find_all(’a’)In [14]: mylist=[] ...: for link in link_list: ...: mylist.append(’http://www.qu.la’+link.get(’href’)) ...: ...:#遍历每个链接,下载文本内容到 本地文本文件i=0 ...: for url in mylist1: ...: re1=requests.get(url) ...: html2=re1.text ...: soup=BeautifulSoup(html2,'html.parser') ...: content=soup.find(id='content').text.replace(’chaptererror();’, ’’) ...: filename=str(i)+’.txt’ ...: with open(filename,’w’)as f: ...: f.write(content) ...: print(’当前小说第{}章已经下载完成’.format(i)) ...: f.close() ...: i=i+1
问题解答
回答1:f.write(content.encode(’utf-8’))
或者
import codecswith codecs.open(filename, ’w’, ’utf-8’) as f: f.write(content)
相关文章:
1. python for循环中的函数只能运行一次?2. 怎样写一个时间到了或是有订单的语音提醒呢?3. javascript - js读取excel其中一列中的一个值是0.3556但是读出来是0.35559999999999997?4. angular.js - angular ui bootstrap 中文显示问题5. 如何解决Centos下Docker服务启动无响应,且输入docker命令无响应?6. html5 - h5页面在iphone上字体变形7. javascript - 关于apply()与call()的问题8. html - 竖线怎么实现9. mysql - SELECT 多個資料表及多個欄位10. web服务器 - ubuntu下布置apache加wsgi加python

网公网安备