前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3 urllib 爬虫乱码问

python3 urllib 爬虫乱码问

作者头像
py3study
发布2020-01-13 11:10:01
5450
发布2020-01-13 11:10:01
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from urllib.request import urlopen

baseUrl = 'http://www.51bengou.com'


def getCover(articleUrl):
    global baseUrl
    html = urlopen(baseUrl+articleUrl).read()
    bsObj = BeautifulSoup(html, 'lxml')
    try:
        # Find internal link of the cover.
        src = bsObj.find('div', {'class': 'cartoon-intro'}).find('img')['src']
        return src
    except AttributeError:
        return None


def getInfo(articleUrl):
    global baseUrl
    html = urlopen(baseUrl+articleUrl)
    bsObj = BeautifulSoup(html, 'lxml')
    try:
        # Find all information.
        infos = bsObj.find('div', {'class': 'cartoon-intro'}).findAll('p', {'class': False})
        items = {}
        # Store in a dict.
        for info in infos[:7]:
            items[info.span.text] = info.text
        return list(items)
    except AttributeError:
        return None


print(getInfo('/cartoon/HuoYingRenZhe/'))

如上程序是一个基于笨狗漫画网的爬虫程序,运行后,发现得到的漫画基本信息输出为乱码。

代码语言:javascript
复制
<meta charset="gb2312">

经查看网页源码发现,这个网页使用了gb2312编码。经我目前学习的编码知识,在程序读取网页时,BeautifulSoup使用了默认的utf-8编码将gb2312编码的字节字符串解码为了Unicode。此时,就出现了乱码,并且可能因为对错误的忽略或者替代,信息已经发生了丢失。

为了解决这个问题,我们应该在使用BeautifulSoup之前,对urlopen得到的对象进行读取,然后使用gb2312编码进行解码,此时问题应该就解决了。

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from urllib.request import urlopen

baseUrl = 'http://www.51bengou.com'


def getCover(articleUrl):
    global baseUrl
    html = urlopen(baseUrl+articleUrl).read().decode('gb2312', 'replace')
    bsObj = BeautifulSoup(html, 'lxml')
    try:
        # Find internal link of the cover.
        src = bsObj.find('div', {'class': 'cartoon-intro'}).find('img')['src']
        return src
    except AttributeError:
        return None


def getInfo(articleUrl):
    global baseUrl
    html = urlopen(baseUrl+articleUrl).read().decode('gb2312', 'replace')
    bsObj = BeautifulSoup(html, 'lxml')
    print(html)
    try:
        # Find all information.
        infos = bsObj.find('div', {'class': 'cartoon-intro'}).findAll('p', {'class': False})
        items = {}
        # Store in a dict.
        for info in infos[:7]:
            items[info.span.text] = info.text
        return list(items)
    except AttributeError:
        return None


print(getInfo('/cartoon/HuoYingRenZhe/'))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档