编码BUG心得记录

昨天学习爬虫的时候,遇到了一个编码方式的bug,先贴出BUG提示:

Traceback (most recent call last):
  File "E:/py code/practice-2.py", line 46, in <module>
    tiebaSpider(url,beginPage,endPage)
  File "E:/py code/practice-2.py", line 35, in tiebaSpider
    writePage(html,filename)
  File "E:/py code/practice-2.py", line 8, in writePage
    with open(filename,'w') as f:
IOError: [Errno 22] invalid mode ('w') or filename: '\xe7\xac\xac1\xe9\xa1\xb5.html'

其中,出错地方的代码为:

def writePage(html,filename):
    print("正在保存 "+filename)

    with open(filename,'w') as f:
        f.write(html)

    print("-"*30)

找了很久,一直以为是路径的问题,将路径修改完后发现也不行,最后在网上查找资料,发现是编码的问题,将代码修改成如下便可以成功运行:

原因分析:

python中的编码小细节

Python中有编码转换的函数,decode(char_set)可以实现其他编码到Unicode的转换,encode(char_set)实现Unicode到其他编码的转换。

 查看Python文档会发现:

    open(filename, 'w')这个方法中,filename这个参数必须是Unicode编码的参数,而我们的代码里面,filename是通过str的相加来得到的,因此需要进行decode编码来转换编码方式。

猜你喜欢

转载自blog.csdn.net/qq_33427267/article/details/81141814