解决 Python3 下 print

发布时间:2019-10-18 09:07:20编辑:auto阅读(2822)

    今天试着使用 Selenium 做爬虫时 print 爬取到的信息时,程序报错,信息如下:

    Traceback (most recent call last):
      File "spider.py", line 19, in <module>
        print(girlsList)
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
    

    在解释器里执行sys.stdout时,返回的结果是

    <_io.TextIOWrapper name='<stdout>' mode='w' encoding='ANSI_X3.4-1968'>

    这里可以发现encoding=”ANSI_X3.4-1968“,而我们的需要的编码是utf-8,所以需要在程序的头部加入如下代码:

    import sys, io
    
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="urf-8")

    这样就可以正常的做输出操作了

    参考信息:解决Python3下打印utf-8字符串出现UnicodeEncodeError的问题

关键字