R网络数据分析之XPath

前言

XPath是一种路径语言。在网络数据分析中我们经常会用到它从HTML或者XML文件中遍历来提取我们要的元素或者属性。XPath功能强大使用方便,本文是对XPath学习的整理及总结。

目录

  1. 节点
  2. 节点关系
  3. XPath谓语
  4. 提取节点元素
  5. 提取节点元素
  6. 总结

1、节点

在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。树的根被称为文档节点或者根节点。

示例XML文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author> 
  <year>2005</year>
  <price>29.99</price>
</book>
<book>
  <title lang="cn">R语言编程艺术</title>
  <author>Matloff</author> 
  <year>2006</year>
  <price>50</price>
</book>
<book>
  <title lang="cn">ggplot2:数据分析与图形艺术</title>
  <author>Wickham</author> 
  <year>2009</year>
  <price>45</price>
</book>
</bookstore>

这个XML文件定义了一个书架,一共有3本书,每本书有书名、作者、年代、以及价格。

先来看个小例子取出三本书的书名:

library(XML)
parsed_doc <- xmlParse(file = 'Example.xml',encoding = 'UTF-8',
ignoreBlanks = TRUE)
##root <- xmlRoot(parsed_doc)
books <- xpathSApply(parsed_doc,path = '//book/title',xmlValue)
> books
[1] "Harry Potter"                "R语言编程艺术"               "ggplot2:数据分析与图形艺术"

2、节点关系

这里举一个例子:取出英文书籍的节点。

parents <- xpathSApply(parsed_doc,path = '//book/title[@lang="en"]/parent::*')
> parents
[[1]]
<book>
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book> 

3、XPath谓语

谓语就是能针对节点的名字、值、属性进行调用的简单函数。



返回书的作者:

authors <- xpathSApply(parsed_doc,path = '//*[name()="author"]')
[[1]]
<author>J K. Rowling</author> 

[[2]]
<author>Matloff</author> 

[[3]]
<author>Wickham</author> 

返回倒数第二本书的作者:

last_second_author <- xpathSApply(parsed_doc,path = '//book[last()-1]/author')
> last_second_author
[[1]]
<author>Matloff</author> 

4、提取节点元素

我们通过不关心节点的整体,只关心节点特定的值,例如值。我们已经运用xpathSApply来返回匹配特定主角的节点,我们只需要在函数调用过程中把一个提取函数传递给fun参数就可以了。


提取所有书名节点的属性

langs <- xpathSApply(parsed_doc,path ='//book/title',xmlAttrs)

> langs
lang lang lang
"en" "cn" "cn"

提取book下的所有书出版的年代

years <- xpathSApply(parsed_doc,path ='//book/year',xmlValue)

> years
[1] "2005" "2006" "2009"

我们也可以自己扩展fun参数对节点进行什么有用的处理。如下示例把书编写的语言提出来取做下转换:

langfun <- function(x)
{
  lang <- xmlGetAttr(x,'lang')
  lang <- ifelse(lang=='cn','chinese','english')
  return(lang)
}
langs <-xpathSApply(parsed_doc,path ='//book/title',langfun)
langs
[1] "english" "chinese" "chinese"

5、XPATH辅助性小工具

SelectorGadget是一个开源的小工具,它能通过鼠标点击的方法,对创建XPath语句的过程进行简化。Hadley Wickham写过一篇这个小工具的使用教程。

点击查看Selectorgadet的使用方法

6、总结

XPATH对于做爬虫网络数据分析来说还是很重要的值得花点时间学习下。

参考资料

1、基于R语言的自动数据收集--网络抓取和文本挖掘实用指南

2、XPath 教程

发布于 2017-08-31 21:27