爬虫学习——编解码错误

爬虫学习——编解码错误

一.编码

1.对腾讯首页进行解析,筛选出了视觉焦点板块中对应图片的标题

视觉焦点
2.对筛选的文本进行编码
3.输出标题的编码类型以及标题的文本
4.得到乱码

C:\Python27\ArcGIS10.2\python.exe C:/Users/Administrator/PycharmProjects/untitled1/web_parse.py
<type 'unicode'>
ÒÕÈËÓÃ2Íò¸ùÖñÇ©Ôì³öÁÉÄþ½¢
<type 'unicode'>
̨·ç¹ýºó ÊÜÉ˹ÅÊ÷´òµõÆ¿
<type 'unicode'>
º«¹úÅ®ÌØÖÖ±øͽÊÖÅüשÅü¾ÆÆ¿
<type 'unicode'>
Á½Å®Ò»ÄÐÉîÒ¹·¿ÖÐÎü¶¾±»×¥
<type 'unicode'>
¼Ö¾²ö©Æë¼ç¶Ì·¢µÇ·âÃæ
<type 'unicode'>
ÐÇ×ùÃ÷ÐǵÄ͵Çé´«ÎÅ 
<type 'unicode'>
´ú¿Î½Ìʦ¶ÀÊØÉîɽ½Ìѧµã30Äê
<type 'unicode'>
ÃÀ¹úÇáÉݺóµÄÖйú¼Ò×å
<type 'unicode'>

´´Òâ¡°ÄæÊÀ½ç¡± ÐéʵÄѱæ
<type 'unicode'>
ÂÞÈûËþºÅ³¤Ãß67PåçÐÇ
<type 'unicode'>
ÈÕ±¾Ò²ÍƳöȫ͸Ã÷²ÞËù
<type 'unicode'>
ΪºÎ»áÉú²¡£¿½ÒÃØÒµÕϲ¡Ô­Òò
<type 'unicode'>
ÄÌÄ̻ң¬µ½µ×ÊʺÏË­£¿
<type 'unicode'>
ÖÕ½áµÄ³ãÌìʹ¿Ë³³cos
<type 'unicode'>
·¶±ù±ù´ó¶ÐØС¶±³Óеã˧
<type 'unicode'>
ÀÖPro 3ÆÀ²â£ºæçÁú821ÈçºÎ£¿
<type 'unicode'>
±±ÌåÒ»×ÖÂíУ»¨×ߺìÍøÂç

Process finished with exit code 0
5.python代码为下
    Soup = BeautifulSoup(urllib2.urlopen('http://www.qq.com'))
    titles = Soup.select('#picFocusUl > li:nth > p > a')

    for title in titles:
        title.encode('UTF-8')
        print type(title.get_text())
        print(title.get_text())

二.解码

从网上搜素得到,字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
而腾讯首页采用的的是GBK编码:
腾讯首页编码
python采用的是UTF-8编码。
于是便试想将原来筛选出来的文档解码成为unicode中间编码,再转化成utf—8编码:

Soup = BeautifulSoup(urllib2.urlopen('http://www.qq.com'))
titles = Soup.select('#picFocusUl > li:nth > p > a')

for title in titles:
    title.decode('gbk')
    title.encode('UTF-8')
    print type(title.get_text())
    print(title.get_text())

但是却有错误:

C:\Python27\ArcGIS10.2\python.exe C:/Users/Administrator/PycharmProjects/untitled1/web_parse.py
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/untitled1/web_parse.py", line 14, in <module>
    title.decode('gbk')
  File "C:\Python27\ArcGIS10.2\lib\site-packages\bs4\element.py", line 1056, in decode
    indent_space = (' ' * (indent_level - 1))
TypeError: unsupported operand type(s) for -: 'str' and 'int'

Process finished with exit code 1

还不懂原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值