requests爬虫结果不显示中文。

新手上路,请多包涵

lz小白,刚开始接触爬虫,代码如下
图片描述

但是教程里r.text的结果是:

图片描述

求教,是哪里出问题了导致我的结果无法显示中文?

阅读 8k
4 个回答

情景1:

print(rep.text[:1000])  #显示中文

情景2:unicode转str

print(rep.text.encode('utf-8','ignore')[:1000])

r.text[:1000].encode("utf-8")
r.text[:1000].encode("GB2312")
r.text[:1000].decode("utf-8")
r.text[:1000].decode("gb2312")

四种方法,一个一个试试,看看那个可以了就确定用那个。

python2.x中, 字符串分为两种,有u前缀和没有u前缀, 直接用print 打印,可以显示

>>> hi = '你好'
>>> 
>>> hi
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> type(hi)
<type 'str'>
>>> print hi
你好
>>> hi = u'你好'
>>> hi
u'\u4f60\u597d'
>>> type(hi)
<type 'unicode'>
>>> print hi
你好
r.encoding = "utf-8"
r.text[:1000]

编码改成"utf-8"乱码

print(r.text[:1000])

结果:

gbk
GB2312
<!-- shouji -->
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
    <title>【华为麦芒6】华为 HUAWEI 麦芒 6 全网通 4GB+64GB版 流光金 移动联通电信4G手机 双卡双待【行情 报价 价格 评测】-京东</title>
    <meta name="keywords" content="HUAWEI麦芒6,华为麦芒6,华为麦芒6报价,HUAWEI麦芒6报价"/>
    <meta name="description" content="【华为麦芒6】京东JD.COM提供华为麦芒6正品行货,并包括HUAWEI麦芒6网购指南,以及华为麦芒6图片、麦芒6参数、麦芒6评论、麦芒6心得、麦芒6技巧等信息,网购华为麦芒6上京东,放心又轻松" />
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/4971133.html">
    <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/4971133.html">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <link rel="canonical" href="//item.jd.com/4971133.html"/>
        <link rel="dns-prefetch" href="//misc.360buyimg.com"/>
    <link rel="dns-prefetch" href="//static.360buyimg.com"/>
    <link rel="dns-prefetch" href="//img10.360buyimg.com"/
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题