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 相关文章推荐
Django与遗留的数据库整合的方法指南
Jul 24 Python
Python中元组,列表,字典的区别
May 21 Python
使用paramiko远程执行命令、下发文件的实例
Oct 01 Python
使用Python搭建虚拟环境的配置方法
Feb 28 Python
python设定并获取socket超时时间的方法
Jan 12 Python
Python pandas DataFrame操作的实现代码
Jun 21 Python
Python 实现数据结构-堆栈和队列的操作方法
Jul 17 Python
python 类之间的参数传递方式
Dec 20 Python
Python打包模块wheel的使用方法与将python包发布到PyPI的方法详解
Feb 12 Python
Python3 操作 MySQL 插入一条数据并返回主键 id的实例
Mar 02 Python
Python优秀开源项目Rich源码解析的流程分析
Jul 06 Python
Django def clean()函数对表单中的数据进行验证操作
Jul 09 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序列化反序列化的方法
2015/10/27 PHP
PHP动态地创建属性和方法, 对象的复制, 对象的比较,加载指定的文件,自动加载类文件,命名空间
2016/05/06 PHP
PHPWind9.0手动屏蔽验证码解决后台关闭验证码但是依然显示的问题
2016/08/12 PHP
PHP判断是否是微信打开,浏览器打开的方法
2018/03/14 PHP
laravel框架添加数据,显示数据,返回成功值的方法
2019/10/11 PHP
Thinkphp 框架扩展之Widget扩展实现方法分析
2020/04/23 PHP
PHP设计模式入门之迭代器模式原理与实现方法分析
2020/04/26 PHP
IE event.srcElement和FF event.target 功能比较
2010/03/01 Javascript
使用HTML+CSS+JS制作简单的网页菜单界面
2015/07/27 Javascript
ClearTimeout消除闪动实例代码
2016/02/29 Javascript
详解AngularJS 模态对话框
2016/04/07 Javascript
Javascript json object 与string 相互转换的简单实现
2016/09/27 Javascript
EasyUI修改DateBox和DateTimeBox的默认日期格式示例
2017/01/18 Javascript
js弹出窗口简单实现代码
2017/03/22 Javascript
用ES6的class模仿Vue写一个双向绑定的示例代码
2018/04/20 Javascript
微信小程序的部署方法步骤
2018/09/04 Javascript
jQuery实现的3D版图片轮播示例【滑动轮播】
2019/01/18 jQuery
微信小程序新手教程之启动页的重要性
2019/03/03 Javascript
vue 列表页跳转详情页获取id以及详情页通过id获取数据
2019/03/27 Javascript
vue.js多页面开发环境搭建过程
2019/04/24 Javascript
Node.JS发送http请求批量检查文件中的网页地址、服务是否有效可用
2019/11/20 Javascript
angular8和ngrx8结合使用的步骤介绍
2019/12/01 Javascript
详解react组件通讯方式(多种)
2020/05/06 Javascript
在Python中使用itertools模块中的组合函数的教程
2015/04/13 Python
Python图算法实例分析
2016/08/13 Python
python读取与写入csv格式文件的示例代码
2017/12/16 Python
Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例
2018/07/27 Python
Python开发的十个小贴士和技巧及长常犯错误
2018/09/27 Python
详解python statistics模块及函数用法
2019/10/27 Python
Python通过递归函数输出嵌套列表元素
2020/10/15 Python
HTML5 input元素类型:email及url介绍
2013/08/13 HTML / CSS
Ajax的优点和缺点
2014/11/21 面试题
建筑实习自我鉴定
2013/10/18 职场文书
有关环保的标语
2014/06/13 职场文书
省委召开党的群众路线教育实践活动总结大会报告
2014/10/21 职场文书
那些美到让人窒息的诗句,值得你收藏!
2019/08/20 职场文书