如图,往一个html文件里写<a>标签,带变量的字符串写不进去,在write('<a></a>')可以写进去,不知为什么
æç¨ç2.7 æ¯å¯ä»¥åå ¥çï¼æ¥¼ä¸»æå¼å¸¸æå°åºæ¥ççå ·ä½æ¯ä»ä¹å¼å¸¸
追é®titleæ¯ä»ç½ç«éç¬ä¸æ¥çæ±åï¼åºè¯¥æ¯ç¼ç çé®é¢
é误æ示ï¼
'ascii' codec can't encode characters in position 77-97: ordinal not in range(128)
温馨提示:答案为网友推荐,仅供参考
第1个回答 2016-10-07
这边测试没有问题,最好发一下完整的程序。下面是测试的代码
def addHtmlNode(self, title, href):
fout = open('list.htm', 'a+')
node = "<br/><a href='%s'>%s</a>" % (href, title)
print(node)
try:
fout.write(node)
fout.flush()
except:
print("error")
print("3")
fout.close()
print("4")
h = htm()
h.addHtmlNode('hello', 'url')追问
title是从网站里爬下来的汉字,应该是编码的问题
错误提示:
'ascii' codec can't encode characters in position 77-97: ordinal not in range(128)
Python在处理多语言方面确实有些问题,几个建议
1、open语句指定文件的编码encoding
open(file,
mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True,
opener=None)
2、另存源代码文件,选择合适的编码
3、爬下来的汉字保存成字节,回避Python的编码处理问题