XPath - 提取属性

时间:2014-09-17 05:26:53

标签: r xpath

如何使用XPath从此代码中提取href属性?

<a 
itemprop="url" 
name="1055782959" 
href=“abc123”>
<span itemprop="name">myName</span>
</a>

编辑: 关于我正在尝试做什么的更多细节。 我实际上想用R从网站上挖掘一些数据。 我尝试了以下内容,但它无法正常工作:

xpathSApply(doc,"a/@href",xmlValue)

doc是HTML页面。

编辑: 获取网页的代码:

fileUrl <- "http://www.gumtree.com.au/s-cars-vans-utes/toyota/page-1/k0c18320"
#doc <- htmlTreeParse(fileUrl, useInternal=T)

getLinks <- function() { 
  links <- character() 
  list(a = function(node, ...) { 
    links <<- c(links, xmlGetAttr(node, "href"))
    node 
  }, 
  links = function()links)
}

h1 <- getLinks
doc <- htmlTreeParse(fileUrl, useInternal = TRUE, handlers = h1); 
h1$links()

1 个答案:

答案 0 :(得分:2)

我喜欢getLinks获取href个链接。

> library(XML)
> txt <- '<a 
 itemprop="url" 
 name="1055782959" 
 href="abc123">
     <span itemprop="name">myName</span>
     </a>'     
> h1 <- getLinks()
> htmlParse(txt, asText = TRUE, handlers = h1)
> h1$links()
[1] "abc123"

如果您已有html文档doc,请使用htmlParse(doc, handlers = h1)代替上面的htmlParse来电。 getLinks功能可在?htmlParse的示例中找到,并可用于获取其他属性。

getLinks <- function() { 
        links <- character() 
        list(a = function(node, ...) { 
                    links <<- c(links, xmlGetAttr(node, "href"))
                    node 
                 }, 
             links = function()links)
}
相关问题