关于用python把中文字符写入TXT文件的问题

掌上鹅 2017-11-20 06:28:51
刚学python爬虫,于是试着爬一个网页的文本内容,然后想它存入一个TXT文件,然后呢!就是出现了这个错误。
求大佬解答。
#_*_conding=utf-8_*_
import urllib
import urllib2
import re

url = 'http://news.xinhuanet.com/rwk/2013-02/06/c_124330585.htm'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
try:
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8')
pattern = re.compile(r'<p>(.*?)<\/p>')
items = re.findall(pattern, content)
fl = open('1.txt', 'a')
for line in items:
fl.write(line)
fl.write("\n")
f1.close()

except urllib2.URLError, e:
if hasattr(e, "code"):
print e.code
if hasattr(e, "reason"):
print e.reason

报错代码:UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128)
...全文
1263 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
克念 2018-08-17
  • 打赏
  • 举报
回复 1
记得encode为utf-8之后,使用byte方式写入到文件中。因为encode的结果是字节码,所以必须要以字节码的方式写到文件。
那么把写入方式变为字节码,直接在

fl = open('1.txt', 'ab') #在后面加上b,表示以字节码方式写入
for line in items:
fl.write(line.encode('utf-8'))
fl.write("\n")
f1.close()
linanbox212 2017-11-21
  • 打赏
  • 举报
回复
import sys reload(sys) sys.setdefaultencoding('utf8')
掌上鹅 2017-11-20
  • 打赏
  • 举报
回复
引用 1 楼 oyljerry 的回复:
用utf8写文件

fl = open('1.txt', 'a')
    for line in items:
        fl.write(line.encode('utf-8'))
        fl.write("\n")
    f1.close()

可以存了,但有一个问题就是这个TXt文件打开怎么乱码了?该怎么解决?
oyljerry 2017-11-20
  • 打赏
  • 举报
回复
用utf8写文件

fl = open('1.txt', 'a')
    for line in items:
        fl.write(line.encode('utf-8'))
        fl.write("\n")
    f1.close()

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧