前几天看到有介绍《Python网络数据采集》这本书,本来想买的,不过亚马逊上还没看到出货。
就找了本英文版的先看了,英文版名字是:Web Scraping with Python
这几天先把第一部分(1-2章)看完了,先做一个总结。
这2章主要讲第一个网络爬虫和HTML解析。
具体内容还是需要去看书,我这里主要提一个内容及示例索引。
在序言里提到的爬虫应用的通用步骤
1.从URL获取对应的HTML代码(Retrieving HTML data from a domain name)
2.解析HTML代码获取想要的信息(Parsing that data for target information)
3.保存获取的信息(Storing the target information)
4.访问其他页面重复以上过程(Optionally, moving to another page to repeat the process)
一些基本概念及安装准备工作
这本书使用Python 3, Scrapy 1.0版还不能支持Python 3,所以只是提了一下,
具体还使用urllib和beautifulsoup,注意在Python 3中原来的urllib2被改名成urllib
准备工作很简单,直接安装beautifulsoup姐可以了
pip install beautifulsoup4
我的测试环境还使用pyenv,先激活,再起IPython Notebook服务
pyenv activate env351
pip install beautifulsoup4
jupyter notebook
我将示例代码存成ipynb,便于查看,具体大家也可以用来参照,内容见末尾的附件
Chpt01.开始第一个web爬虫
第一章就介绍了总的使用方法
1.使用urlopen打开网页
2.使用BeautifulSoup解析网页
具体看一下示例就可以了:
Chpt 01 示例(https://github.com/REMitchell/python-scraping/tree/master/chapter1)
1-basicExample.py 读一个网页
2-beautifulSoup.py读一个网页标题,使用beautifulSoup解析
3-exceptionHandling.py( 在(2)的基础上增加异常处理
Chpt02.解析HTML
解析HTML的一般步骤
1.找到对象
bsObj.findAll("span", {"class":"red"}) #1-selectByClass.py 代表随书的示例代码,下同
bsObj.findAll(id="text") #2selectByAttribute.py
2.遍历对象list和访问对象的层次节点
for name in bsObj.findAll("span", {"class":"green"}):
print(name.get_text())
3.如果需要可以引用对象的各层级对象
bsObj.find("table",{"id":"giftList"}).children #3-findDescendants.py
bsObj.find("table",{"id":"giftList"}).tr.next_siblings #4-findSiblings.py
bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text() #4-findSiblings.py
4.直接取对应代码或get_text()输出对应文本
print(bsObj.findAll("span", {"class":"red"})[0])
print(bsObj.findAll("span", {"class":"red"})[0].get_text())
5.使用正则表达式或lambda表达式做更多匹配
bsObj.findAll("img", {"src":re.compile("\.\.\/img\/gifts/img.*\.jpg")}) #5-findParents.py
bsObj.findAll(lambda tag: len(tag.attrs) == 2) #6-regularExpressions.py
Chpt 02 示例(https://github.com/REMitchell/python-scraping/tree/master/chapter2)
(1)#1-selectByClass.py
(2)#2selectByAttribute.py
(3)#3-findDescendants.py
(4)#4-findSiblings.py
(5)#5-findParents.py
(6)#6-regularExpressions.py
(7)#7-lambdaExpressions.py
附件是我整理的ipynb