import urllib.request
response = urllib.request.urlopen('http://www.12306.cn/mormhweb/')
html = response.read()
print(html)
上面的代码正常但是运行的时候结果遇到中文会以\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80代替,这是一种byte字节。
python 3输出位串,而不是可读的字符串,需要对其进行转换
使用str(string[, encoding])对数组进行转换
str(response.read(),'utf-8')
import urllib.request response = urllib.request.urlopen('http://www.12306.cn/mormhweb/')
html =str(response.read(),'utf-8') print(html)
这样就解决了中文不能输出问题,效果如下
![pycharm爬虫运行后console中文出现xe4\xb8\乱码的解决方法 pycharm爬虫运行后console中文出现xe4\xb8\乱码的解决方法](https://image.shishitao.com:8440/aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzU4Ni80MDRkMzY4ZGZiOGU3NGIwN2QzZDYxMjNjZTQ4YWM3YS5wbmc%3D.png?w=700&webp=1)