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简单实现enum功能的方法
Apr 25 Python
浅谈python字典多键值及重复键值的使用
Nov 04 Python
利用numpy实现一、二维数组的拼接简单代码示例
Dec 15 Python
python实现画圆功能
Jan 25 Python
Python之列表的插入&amp;替换修改方法
Jun 28 Python
python 检查是否为中文字符串的方法
Dec 28 Python
python3.6使用tkinter实现弹跳小球游戏
May 09 Python
解决python文件双击运行秒退的问题
Jun 24 Python
基于Python的ModbusTCP客户端实现详解
Jul 13 Python
Python序列类型的打包和解包实例
Dec 21 Python
弄清Pytorch显存的分配机制
Dec 10 Python
使用Python下载抖音各大V视频的思路详解
Feb 06 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_screw 1.5:php加密: 安装与使用详解
2013/06/20 PHP
Codeigniter(CI)框架分页函数及相关知识
2014/11/03 PHP
js利用div背景,做一个竖线的效果。
2008/11/22 Javascript
Javascript String对象扩展HTML编码和解码的方法
2009/06/02 Javascript
jQuery垂直多级导航菜单代码分享
2015/08/18 Javascript
在javaScript中检测数据类型的几种方式小结
2017/03/04 Javascript
canvas基础绘制-绚丽倒计时的实例
2017/09/17 Javascript
JavaScript的setter与getter方法
2017/11/29 Javascript
Vue组件之自定义事件的功能图解
2018/02/01 Javascript
Mac下通过brew安装指定版本的nodejs教程
2018/05/17 NodeJs
jQuery实现监听下拉框选中内容发生改变操作示例
2018/07/13 jQuery
Node.js如何对SQLite的async/await封装详解
2019/02/14 Javascript
详解NodeJS Https HSM双向认证实现
2019/03/12 NodeJs
Vue组件系列开发之模态框
2019/04/18 Javascript
如何使用CSS3+JQuery实现悬浮墙式菜单
2019/06/18 jQuery
如何在wxml中直接写js代码(wxs)
2019/11/14 Javascript
layui写后台表格思路和赋值用法详解
2019/11/14 Javascript
卸载vue2.0并升级vue_cli3.0的实例讲解
2020/02/16 Javascript
微信小程序开发(一):服务器获取数据列表渲染操作示例
2020/06/01 Javascript
Python实现提取谷歌音乐搜索结果的方法
2015/07/10 Python
Python实现的选择排序算法原理与用法实例分析
2017/11/22 Python
Python-OpenCV基本操作方法详解
2018/04/02 Python
Python面向对象之类和实例用法分析
2019/06/08 Python
复化梯形求积分实例——用Python进行数值计算
2019/11/20 Python
python求最大公约数和最小公倍数的简单方法
2020/02/13 Python
Pygame框架实现飞机大战
2020/08/07 Python
Django配置Bootstrap, js实现过程详解
2020/10/13 Python
保时捷设计:Porsche Design
2019/03/30 全球购物
肯尼迪就职演说稿
2013/12/31 职场文书
早餐连锁店计划书
2014/01/08 职场文书
大班开学家长寄语
2014/04/04 职场文书
信电学院毕业生自荐书
2014/05/24 职场文书
2014年员工工作总结范文
2014/11/18 职场文书
经理岗位职责
2015/02/02 职场文书
化验室岗位职责
2015/02/14 职场文书
卫生保健工作总结2015
2015/05/18 职场文书