Python使用Beautiful Soup包编写爬虫时的一些关键点


Posted in Python onJanuary 20, 2016

1.善于利用soup节点的parent属性

比如对于已经得到了如下html代码:

<td style="padding-left:0" width="60%"><label>November</label>
<input type="Hidden" id="cboMonth1" name="cboMonth1" value="11">
</td><td style="padding-right:0;" width="40%">
  <label>2012</label>
  <input type="Hidden" id="cboYear1" name="cboYear1" value="2012">
</td>

的soup变量eachMonthHeader了。

想要提取其中的

Month的label的值:November

和Year的label的值:2012

最简单,也是最省事的办法是,直接搜两个label,然后肯定会找到这两个label,然后分别对应着Month和Year的label,然后获得对应的string即可:

foundTwoLabel = eachMonthHeader.findAll("label");
print "foundTwoLabel=",foundTwoLabel;
monthLabel = foundTwoLabel[0];
yearLabel = foundTwoLabel[1];
 
monthStr = monthLabel.string;
yearStr = yearLabel.string;
 
print "monthStr=",monthStr; # monthStr= November
print "yearStr=",yearStr; # yearStr= 2012

但是很明显,这样的逻辑性很不好,而且万一处理多个这样的soup变量,而且两者的顺便颠倒了,那么结果也就错误了。

此时,可以考虑利用soup变量的parent属性,从一个soup变量本身,获得其上一级的soup变量。
示例代码如下:

# <td style="padding-left:0" width="60%"><label>November</label>
# <input type="Hidden" id="cboMonth1" name="cboMonth1" value="11">
# </td><td style="padding-right:0;" width="40%">
  # <label>2012</label>
  # <input type="Hidden" id="cboYear1" name="cboYear1" value="2012">
# </td>
foundCboMonth = eachMonthHeader.find("input", {"id":re.compile("cboMonth\d+")});
#print "foundCboMonth=",foundCboMonth;
tdMonth = foundCboMonth.parent;
#print "tdMonth=",tdMonth;
tdMonthLabel = tdMonth.label;
#print "tdMonthLabel=",tdMonthLabel;
monthStr = tdMonthLabel.string;
print "monthStr=",monthStr;
 
foundCboYear = eachMonthHeader.find("input", {"id":re.compile("cboYear\d+")});
#print "foundCboYear=",foundCboYear;
tdYear = foundCboYear.parent;
#print "tdYear=",tdYear;
tdYearLabel = tdYear.label;
#print "tdYearLabel=",tdYearLabel;
yearStr = tdYearLabel.string;
print "yearStr=",yearStr;

我们再来看一个例子:

from BeautifulSoup import BeautifulSoup 
doc = ['<html><head><title>Page title</title></head>',
    '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
    '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
    '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()
# <html>
# <head>
#  <title>
#  Page title
#  </title>
# </head>
# <body>
#  <p id="firstpara" align="center">
#  This is paragraph
#  <b>
#   one
#  </b>
#  .
#  </p>
#  <p id="secondpara" align="blah">
#  This is paragraph
#  <b>
#   two
#  </b>
#  .
#  </p>
# </body>
# </html>

这个例子中,<HEAD> Tag的parent是<HTML> Tag. <HTML> Tag 的parent是BeautifulSoup 剖析对象自己。 剖析对象的parent是None. 利用parent,你可以向前遍历剖析树。

soup.head.parent.name
# u'html'
soup.head.parent.parent.__class__.__name__
# 'BeautifulSoup'
soup.parent == None
# True

2.当解析非UTF-8或ASCII编码类型的HTML时,需要指定对应的字符编码

当html为ASCII或UTF-8编码时,可以不指定html字符编码,便可正确解析html为对应的soup:

#这里respHtml是ASCII或UTF-8编码,此时可以不指定编码类型,即可正确解析出对应的soup
soup = BeautifulSoup(respHtml);

当html为其他类型编码,比如GB2312的话,则需要指定相应的字符编码,BeautifulSoup才能正确解析出对应的soup:

比如:

#此处respHtml是GB2312编码的,所以要指定该编码类型,BeautifulSoup才能解析出对应的soup
htmlCharset = "GB2312";
soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset);
Python 相关文章推荐
简单介绍利用TK在Python下进行GUI编程的教程
Apr 13 Python
读写json中文ASCII乱码问题的解决方法
Nov 05 Python
Python实现的字典值比较功能示例
Jan 08 Python
python @property的用法及含义全面解析
Feb 01 Python
python斐波那契数列的计算方法
Sep 27 Python
Python查找最长不包含重复字符的子字符串算法示例
Feb 13 Python
pycharm new project变成灰色的解决方法
Jun 27 Python
python 爬取学信网登录页面的例子
Aug 13 Python
使用virtualenv创建Python环境及PyQT5环境配置的方法
Sep 10 Python
Python缓存技术实现过程详解
Sep 25 Python
基于Python实现扑克牌面试题
Dec 11 Python
Django多层嵌套ManyToMany字段ORM操作详解
May 19 Python
Python制作爬虫抓取美女图
Jan 20 #Python
编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
Jan 20 #Python
以视频爬取实例讲解Python爬虫神器Beautiful Soup用法
Jan 20 #Python
使用Python的urllib和urllib2模块制作爬虫的实例教程
Jan 20 #Python
使用python实现省市三级菜单效果
Jan 20 #Python
八大排序算法的Python实现
Jan 28 #Python
详解C++编程中一元运算符的重载
Jan 19 #Python
You might like
解析PHP获取当前网址及域名的实现代码
2013/06/23 PHP
php中filter函数验证、过滤用户输入的数据
2014/01/13 PHP
浅谈php中的循环while、do...while、for、foreach四种循环
2016/11/05 PHP
postman的安装与使用方法(模拟Get和Post请求)
2018/08/06 PHP
PHP addcslashes()函数讲解
2019/02/03 PHP
PHP中__set()实例用法和基础讲解
2019/07/23 PHP
php+laravel依赖注入知识点总结
2019/11/04 PHP
SlideView 图片滑动(扩展/收缩)展示效果
2010/08/01 Javascript
再论Javascript下字符串连接的性能
2011/03/05 Javascript
基于dom编程中 动态创建与删除元素的使用
2013/04/17 Javascript
js动态为代码着色显示行号
2013/05/29 Javascript
js document.write()使用介绍
2014/02/21 Javascript
js调试系列 断点与动态调试[基础篇]
2014/06/18 Javascript
浅谈js 闭包引起的内存泄露问题
2015/06/22 Javascript
javascript中加var和不加var的区别 你真的懂吗
2016/01/06 Javascript
Angular 路由route实例代码
2016/07/12 Javascript
Bootstrap基本组件学习笔记之列表组(11)
2016/12/07 Javascript
JavaScript继承与多继承实例分析
2018/05/26 Javascript
js中自定义react数据验证组件实例详解
2018/10/19 Javascript
python对json的相关操作实例详解
2017/01/04 Python
Python学习小技巧总结
2018/06/10 Python
pandas 强制类型转换 df.astype实例
2020/04/09 Python
如何用Python绘制3D柱形图
2020/09/16 Python
CSS超出文本指定宽度用省略号代替和文本不换行
2016/05/05 HTML / CSS
html5 http的轮询和Websocket原理
2018/10/19 HTML / CSS
惠普墨西哥官方商店:HP墨西哥
2016/12/01 全球购物
阿迪达斯墨西哥官方网站:adidas墨西哥
2017/11/03 全球购物
什么是索引指示器
2012/08/20 面试题
高二生物教学反思
2014/01/27 职场文书
企业安全生产承诺书
2014/05/22 职场文书
社区巾帼文明岗事迹材料
2014/06/03 职场文书
贸易经济专业自荐书
2014/06/29 职场文书
介绍信的写法
2015/01/31 职场文书
幼儿园个人总结
2015/02/28 职场文书
标准发言稿结尾
2019/07/18 职场文书
Nginx利用Logrotate实现日志分割
2022/05/20 Servers