sublime-text - python爬虫编码问题
PHP中文网
PHP中文网 2017-04-18 10:10:29
0
8
398
PHP中文网
PHP中文网

认证高级PHP讲师

Antworte allen(8)
巴扎黑

试试不用元组

print h2, a

应该还是遗留的编码问题

print的时候实际上调用了tuple的__str__()

>>> h = u'你好'
>>> (h, 8).__str__()
"(u'\\u4f60\\u597d', 8)"
巴扎黑

编码方式不同造成,windows平台的编码一般是gbk过着isoxxx,查阅一下web的编码方式(chrome可查阅),然后将编码转为系统一致就ok了

小葫芦

其实单独输出h2是可以输出中文的,非要向你那样输出元组的话,参考下面代码

from __future__ import unicode_literals
#-*-coding:utf-8-*-
import requests
from bs4 import BeautifulSoup
res = requests.get('http://news.sina.com.cn/china/')
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
for news in soup.select('.news-item'):
    if len(news.select('h2'))>0:
        h2=news.select('h2')[0].text
        a=news.select('a')[0]['href']
        test = str((h2, a))
        print(test.decode("unicode-escape"))
巴扎黑

遇到编码问题,还要是理解编码的历史渊源是是什么,可以看看这篇文章, http://foofish.net/python-cha... 以后遇到编码了就知道如何分析问题了。

大家讲道理

python3

PHPzhong

u''开头说明已经是unicode了,编码没有问题,只是你print的方式有问题,2.7的话改成这样应该就没问题了

print '%s,%s'%(h2, a)
小葫芦

读出来之后 直接转化为字符串就可以了

Ty80

print(h2 + a)

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!