python - 爬取京东页面的文本为乱码
阿神
阿神 2017-04-17 16:27:12
[Python讨论组]

我使用beautiful soup解析京东的界面,把里面的文本全都提取出来,但是打印的时候发现全是乱码。jd的界面使用utf-8编码的,我在解码成gbk时却遇到错误。

下面是代码,请指教。

#encoding=gbk
from bs4 import BeautifulSoup
from bs4 import NavigableString
from bs4 import Comment
from bs4 import Doctype
import urllib2

def walker(soup, indent):
    text=""
    if soup.name is not None:
        for child in soup.children:
            if isinstance(child, NavigableString):
                if len(child) != 1: #如何判断是否为空
                    text = indent + unicode(child).encode('utf-8').strip() #.decode('utf-8').encode('gbk')
            text += walker(child, indent+"\t")
    return text

if __name__ == "__main__":
    soup = BeautifulSoup( urllib2.urlopen("http://item.jd.com/1592573020.html").read()) 
    doctypes=soup.findAll(text=lambda text: isinstance(text, Doctype))
    [doctype.extract() for doctype in doctypes]
    comments = soup.findAll(text=lambda text:isinstance(text, Comment))
    [comment.extract() for comment in comments]

    for script in soup("script"):
        script.extract()
    for noscript in soup("noscript"):
        noscript.extract()
    for style in soup("style"):
        style.extract()
    text=walker(soup, "")
    print "text", text.decode('utf-8').encode('gbk') #这里会出错
阿神
阿神

闭关修行中......

全部回复(2)
高洛峰

http://item.jd.com/1592573020.html
这个页面以GBK编码的,
那么你需要做的时先按GBK解码后,然后再按utf-8编码存入

PHP中文网
text.decode('utf-8').encode('gbk')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号