数据采集技术之在Python中Libxml模块安装与使用XPath

为了使用XPath技术,对爬虫抓取的网页数据进行抽取(如标题、正文等等),之后在Windows下安装libxml2模块(安装后使用的是Libxml模块),该模块含有xpath。

准备

需要的软件包:

安装

Python2.7的安装这里不再赘述

lxml的安装,直接运行exe,会自动找到py27的目录进行安装

使用XPath抽取

下面用一个实例来验证,程序来自redice's Blog的文章:

libxml2库的安装,xpath的使用

#coding:utf-8

import codecs
import sys
#不加如下行,无法打印Unicode字符,产生UnicodeEncodeError错误。?
sys.stdout = codecs.lookup('iso8859-1')[-1](sys.stdout)

from lxml import etree

html = r'''<div>
    <div>redice</div>
    <div id="email">redice@163.com</div>
    <div name="address">中国</div>
    <div>http://www.redicecn.com</div>
</div>'''

tree = etree.HTML(html)

#获取email。email所在的div的id为email
nodes = tree.xpath("//div[@id='email']")
print nodes[0].text

#获取地址。地址所在的div的name为address
nodes = tree.xpath("//div[@name='address']")
print nodes[0].text

#获取博客地址。博客地址位于email之后兄弟节点的第二个
nodes = tree.xpath("//div[@id='email']/following-sibling::div[2]")
print nodes[0].text

 

运行结果:

redice@163.com
中国
http://www.redicecn.com

相关推荐

10 thoughts on “数据采集技术之在Python中Libxml模块安装与使用XPath”

  1. 用firebug,或者httpfox追踪它的页面跳转。它请求哪个页面,你就请求哪个页面,如果需要的话,带上之前获取的cookie。分页什么的,得自己找规律,一般都是page=1,page=2这样的格式

    回复

Leave a Comment