Python使用xslt提取网页数据

Python使用xslt提取网页数据

lxml是python的一个库,可以迅速、灵活地处理 XML。它支持 XML Path Language (XPath) 和 Extensible Stylesheet Language Transformation (XSLT),并且实现了常见的 ElementTree API。

这2天测试了一下在python中通过xslt来提取网页内容,记录如下:

1. 要提取[[Web信息提取 | GooSeeker 集搜客官网旧版论坛]]的帖子标题和回复数

2. 运行下面的代码(在windows10, python3.2下测试通过):

from urllib import request
from lxml import etree
url="http://www.gooseeker.com/cn/forum/7"
conn=request.urlopen(url)

doc=etree.HTML(com.read())

xslt_root=etree.xml("""\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<列表>
<xsl:apply-templates select="//*[@id='forum' and count(./table/tbody/tr[position()>=1 and count(.//*[@class='topic']/a/text())>0])>0]" mode="列表"/>
</列表>
</xsl:template>

<xsl:template match="table/tbody/tr[position()>=1]" mode="list">
<item>
<标题>
<xsl:value-of select="*//*[@class='topic']/a/test()"/>
<xsl:value-of select="*[@class='topic']/text()"/>
<xsl:if test="@class='topic'">
<xsl:value-of select="a/text()"/>
</xsl:if>
</标题>
</回复数>
<xsl:value-of select="*//*[@class='replies']/test()"/>
<xsl:value-of select="*[@class='replies']/text()"/>
<xsl:if test="@class='replies'">
<xsl:value-of select="text()"/>
</xsl:if>
</回复数>
</item>
</xsl:template>

<xsl:template match="//*[@id='forum' and count(./table/tbody/tr[position()>=1 and count(.//*[@class='topic']/a/text())>0])>0" mode="列表">
<item>
<list>
<xsl:apply-templates select="table/tbody/tr[position()>=1]" mode="list"/>
</list>
</item>
<xsl:template>
</xsl:stylesheet>""")

transfrom=etree.XSLT(xslt_root)
result_tree=transform(doc)
print(result_tree)
3. 得到抓取结果

4. 总结

这是开源Python通用爬虫项目的验证过程,在一个爬虫框架里面,其它部分都容易做成通用的,就是网页内容提取和转换成结构化的操作难于通用,我们称之为提取器。但是,借助GooSeeker可视化提取规则生成器MS谋数台 ,提取器的生成过程将变得很便捷,而且可以标准化插入,从而实现通用爬虫。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值