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 相关文章推荐
python 循环遍历字典元素的简单方法
Sep 11 Python
Python实现简单生成验证码功能【基于random模块】
Feb 10 Python
django的聚合函数和aggregate、annotate方法使用详解
Jul 23 Python
tensorflow求导和梯度计算实例
Jan 23 Python
Python安装与卸载流程详细步骤(图解)
Feb 20 Python
Python3.6 + TensorFlow 安装配置图文教程(Windows 64 bit)
Feb 24 Python
python实现简单的购物程序代码实例
Mar 03 Python
python实现扫雷小游戏
Apr 24 Python
简单了解python关键字global nonlocal区别
Sep 21 Python
matplotlib更改窗口图标的方法示例
Feb 03 Python
Python 实现Mac 屏幕截图详解
Oct 05 Python
python语言中pandas字符串分割str.split()函数
Aug 05 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
DIY实用性框形天线
2021/03/02 无线电
PHP三元运算符的结合性介绍
2012/01/10 PHP
CodeIgniter基本配置详细介绍
2013/11/12 PHP
详解PHP对数组的定义以及数组的创建方法
2015/11/27 PHP
PHP Filter过滤器全面解析
2016/08/09 PHP
PHP数据库编程之MySQL优化策略概述
2017/08/16 PHP
Laravel框架Blade模板简介及模板继承用法分析
2019/12/03 PHP
Maps Javascript
2007/01/22 Javascript
服务器安全设置的几个注册表设置
2007/07/28 Javascript
JQuery 学习笔记 选择器之一
2009/07/23 Javascript
JQuery优缺点分析说明
2010/06/09 Javascript
jQuery Uploadify 上传插件出现Http Error 302 错误的解决办法
2015/12/12 Javascript
Javascript中函数名.length属性用法分析(对比arguments.length)
2016/09/16 Javascript
浅谈js中function的参数默认值
2017/02/20 Javascript
javascript防篡改对象实例详解
2017/04/10 Javascript
ES6新特性:使用export和import实现模块化详解
2017/07/31 Javascript
JavaScript如何获取到导航条中HTTP信息
2017/10/10 Javascript
微信小程序rich-text富文本用法实例分析
2019/05/20 Javascript
解决微信浏览器缓存站点入口文件(IIS部署Vue项目)
2019/06/17 Javascript
python处理PHP数组文本文件实例
2014/09/18 Python
Python3中多线程编程的队列运作示例
2015/04/16 Python
Python实现读取TXT文件数据并存进内置数据库SQLite3的方法
2017/08/08 Python
对numpy的array和python中自带的list之间相互转化详解
2018/04/13 Python
在Python中pandas.DataFrame重置索引名称的实例
2018/11/06 Python
python实现三次样条插值
2018/12/17 Python
Python利用逻辑回归分类实现模板
2020/02/15 Python
Python递归实现打印多重列表代码
2020/02/27 Python
用html5实现语音搜索框的方法
2014/03/18 HTML / CSS
您的网上新华书店:文轩网
2016/08/24 全球购物
加拿大约会网站:EliteSingles.ca
2018/01/12 全球购物
2014年安全生产大检查方案
2014/05/13 职场文书
法律专业大学生职业生涯规划书:向目标一步步迈进
2014/09/22 职场文书
学校党的群众路线教育实践活动对照检查材料
2014/09/24 职场文书
2015会计试用期工作总结
2014/12/12 职场文书
大学生求职意向书
2015/05/11 职场文书
2019最新劳动仲裁申请书!
2019/07/08 职场文书