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使用socket进行简单网络连接的方法
Apr 29 Python
在SAE上部署Python的Django框架的一些问题汇总
May 30 Python
Python3使用PyQt5制作简单的画板/手写板实例
Oct 19 Python
Python tkinter事件高级用法实例
Jan 31 Python
python+pandas+时间、日期以及时间序列处理方法
Jul 10 Python
Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例
Jul 18 Python
Python高斯消除矩阵
Jan 02 Python
Python从list类型、range()序列简单认识类(class)【可迭代】
May 31 Python
Python CSV文件模块的使用案例分析
Dec 21 Python
手动安装python3.6的操作过程详解
Jan 13 Python
pytorch 常用线性函数详解
Jan 15 Python
在django中使用post方法时,需要增加csrftoken的例子
Mar 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
仿Aspnetpager的一个PHP分页类代码 附源码下载
2012/10/08 PHP
php在数据库抽象层简单使用PDO的方法
2015/11/03 PHP
JavaScript版代码高亮
2006/06/26 Javascript
javascript当onmousedown、onmouseup、onclick同时应用于同一个标签节点Element
2010/01/05 Javascript
一些mootools的学习资源
2010/02/07 Javascript
jQuery窗口、文档、网页各种高度的精确理解
2014/07/02 Javascript
使用jquery.upload.js实现异步上传示例代码
2014/07/29 Javascript
javascript将url中的参数加密解密代码
2014/11/17 Javascript
Google 地图API Map()构造器详解
2016/08/06 Javascript
jQuery progressbar通过Ajax请求实现后台进度实时功能
2016/10/11 Javascript
JavaScript获取短信验证码(周期性)
2016/12/29 Javascript
vue.js图片转Base64上传图片并预览的实现方法
2018/08/02 Javascript
vue自定v-model实现表单数据双向绑定问题
2018/09/03 Javascript
jQuery 淡入/淡出效果函数用法分析
2020/05/19 jQuery
为Python的web框架编写MVC配置来使其运行的教程
2015/04/30 Python
Python使用QQ邮箱发送Email的方法实例
2017/02/09 Python
Python实现读取机器硬件信息的方法示例
2018/06/09 Python
Django框架orM与自定义SQL语句混合事务控制操作
2019/06/27 Python
Python 的AES加密与解密实现
2019/07/09 Python
Python3实现zip分卷压缩过程解析
2019/10/09 Python
python用类实现文章敏感词的过滤方法示例
2019/10/27 Python
Python tkinter和exe打包的方法
2020/02/05 Python
Python递归求出列表(包括列表中的子列表)的最大值实例
2020/02/27 Python
HTML5中通过li-canvas轻松实现单图、多图、圆角图绘制,单行文字、多行文字等
2018/11/30 HTML / CSS
Hawes & Curtis官网:英国经典品牌
2019/07/27 全球购物
C#笔试题集合
2013/06/21 面试题
高级护理专业大学生求职信
2013/10/24 职场文书
物理系毕业生自荐书范文
2014/02/22 职场文书
材料工程专业毕业生求职信
2014/03/04 职场文书
幼儿园教师的考核评语
2014/04/18 职场文书
反洗钱宣传活动总结
2014/08/26 职场文书
剖析后OpLog订阅MongoDB的数据变更就没那么难了
2022/02/24 MongoDB
threejs太阳光与阴影效果实例代码
2022/04/05 Javascript
vue项目配置sass及引入外部scss文件
2022/04/14 Vue.js
Vue OpenLayer测距功能的实现
2022/04/20 Vue.js
Golang入门之计时器
2022/05/04 Golang