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 相关文章推荐
paramiko模块安装和使用(远程登录服务器)
Jan 27 Python
Python编程之多态用法实例详解
May 19 Python
详解python时间模块中的datetime模块
Jan 13 Python
python记录程序运行时间的三种方法
Jul 14 Python
利用python求相邻数的方法示例
Aug 18 Python
python3 requests中使用ip代理池随机生成ip的实例
May 07 Python
Python多线程应用于自动化测试操作示例
Dec 06 Python
Python2和Python3之间的str处理方式导致乱码的讲解
Jan 03 Python
ubuntu 18.04搭建python环境(pycharm+anaconda)
Jun 14 Python
keras中的卷积层&amp;池化层的用法
May 22 Python
Python虚拟环境venv用法详解
May 25 Python
Pycharm添加虚拟解释器报错问题解决方案
Oct 13 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
ThinkPHP实现跨模块调用操作方法概述
2014/06/20 PHP
PHP实现UTF-8文件BOM自动检测与移除实例
2014/11/05 PHP
PHP自带方法验证邮箱是否存在
2016/02/01 PHP
Yii2下点击验证码的切换实例代码
2017/03/14 PHP
微信开发之获取JSAPI TICKET
2017/07/07 PHP
Laravel中Facade的加载过程与原理详解
2017/09/22 PHP
JS动态添加与删除select中的Option对象(示例代码)
2013/12/25 Javascript
javascript创建数组之联合数组的使用方法示例
2013/12/26 Javascript
javascript表单验证和Window详解
2014/12/11 Javascript
jquery动感漂浮导航菜单代码分享
2020/04/15 Javascript
Jquery+Ajax+PHP+MySQL实现分类列表管理(下)
2015/10/28 Javascript
AngularJS控制器controller给模型数据赋初始值的方法
2017/01/04 Javascript
Javascript网页抢红包外挂实现分享
2018/01/11 Javascript
jQuery实现checkbox全选功能完整实例
2018/07/12 jQuery
浅谈从React渲染流程分析Diff算法
2018/09/08 Javascript
jQuery实现王者荣耀手风琴效果
2020/01/17 jQuery
在Angular中实现一个级联效果的下拉框的示例代码
2020/05/20 Javascript
深入解析Python中的lambda表达式的用法
2015/08/28 Python
Python利用ORM控制MongoDB(MongoEngine)的步骤全纪录
2018/09/13 Python
解决python通过cx_Oracle模块连接Oracle乱码的问题
2018/10/18 Python
Python 限制线程的最大数量的方法(Semaphore)
2019/02/22 Python
python使用pandas处理大数据节省内存技巧(推荐)
2019/05/05 Python
django之使用celery-把耗时程序放到celery里面执行的方法
2019/07/12 Python
python3.7 利用函数os pandas利用excel对文件名进行归类
2019/09/29 Python
python实现百度OCR图片识别过程解析
2020/01/17 Python
Python数据可视化常用4大绘图库原理详解
2020/10/23 Python
jupyter notebook指定启动目录的方法
2021/03/02 Python
Sneaker Studio捷克:购买运动鞋
2018/07/08 全球购物
英国花园、DIY、电器和家居用品商店:Robert Dyas
2019/03/18 全球购物
汽车专业毕业生推荐信
2013/11/12 职场文书
建设投标担保书
2014/05/13 职场文书
白酒营销策划方案
2014/08/17 职场文书
反四风个人对照检查材料
2014/09/26 职场文书
执法作风整顿剖析材料
2014/10/11 职场文书
《卧薪尝胆》读后感3篇
2019/12/26 职场文书
教你用Python+selenium搭建自动化测试环境
2021/06/18 Python