首页 > 爬取人民日报的评论员文章,碰到问题了,求解答。

爬取人民日报的评论员文章,碰到问题了,求解答。

新手,在学习python爬虫,环境是python3.4,想爬取人民日报评论员文章,现在只怕去了一个网页,代码如下,

import requests
from bs4 import BeautifulSoup
import re

myUrl = "http://cpc.people.com.cn/pinglun/n1/201/0613/c78779-28428425.html"
response = requests.get(myUrl)
soup = BeautifulSoup(response.text, "lxml", from_encoding="gbk")
print(soup.title.string.encode('ISO-8859-1').decode('gbk'))

for a in soup.find_all(style="text-indent: 2em;"):
    print(a.string.encode('ISO-8859-1').decode('gbk'))

网页上出错的源代码如下:
<span style="text-indent: 2em; display: block;" id="paper_num">《 人民日报 》( 2016年06月13日 01 版)</span>
我的出错提示如下:
Traceback (most recent call last):
File "pa_chong_lx.py", line 21, in <module>

print(a.string.encode('ISO-8859-1').decode('gbk'))

AttributeError: 'NoneType' object has no attribute 'encode'
原因分析:
我查找的关键词是style="text-indent: 2em;,这段代码<span style="text-indent: 2em; display: block;" id="paper_num">《 人民日报 》( 2016年06月13日 01 版)</span> 格式与前边的主题文章代码不一样,所以出错,求解答怎么改。

新手,因为编码的问题卡了好久,感觉一步一个坑,步步是坑!python虽然简单,但也正是简单,我不知道哪里出错了,或者是知道错误但不知道怎么改正。


报错原因NoneType类没有encode属性,说明你用soup.find_all()没有匹配到括号内的参数,你试试先匹配一下tag,再匹配style,可能会找到原因,实在不行上正则


找到一个公共的元素,然后用正则来筛选数据吧


原来代码中的链接已经失效,我以 http://cpc.people.com.cn/n1/2016/0628/c404684-28502214.html 中文章为例子。

可以正常工作的代码:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Last Modified time: 2016-06-30 12:32:52

import requests
from bs4 import BeautifulSoup


myUrl = "http://cpc.people.com.cn/n1/2016/0628/c404684-28502214.html"
response = requests.get(myUrl)

response.encoding = response.apparent_encoding

soup = BeautifulSoup(response.text)
print soup.title.string

for a in soup.find_all(style="text-indent: 2em;"):
    if a.string:
        print a.string

运行结果:

这里遇到的编码问题很常见,简单来说就是 requests 猜错了网页的编码方式。

requests 取得response 后,会根据 headers 中给出的编码来解码拿到的数据,如果响应 header 没有指定编码,则默认指定为 ISO-8859-1(encoding 属性)。好在 requests 还可以根据内容猜测编码方案,推测的结果保存在 apparent_encoding 属性中,针对人民日报评论,这里是 GB2312。所以,只需要制定 encoding = apparent_encoding,然后获取text 即可得到正确的解码结果。(注意apparent_encoding并不能保证 100%正确)

requests 文档部分可以参考Response Content
关于编码的理解,可以参考:人机交互之字符编码和 五分钟战胜 Python 字符编码。
关于requests 编码解析的详细内容,参考Python + Requests 编码问题

编码确实是一个坑,不过搞清楚了,就很容易避过去。

【热门文章】
【热门文章】