2014-10-05 19 views
0

当我在表达式中使用XPath 1.0的substring-before或-after时,会发生某些情况,导致我的后续xmlValue调用引发错误。下面的代码显示XPath表达式可以很好地与httr配合使用,但是对RCurl无效。为什么XPath 1.0和RCurl与httr的结果不同,在表达式之前使用子字符串

require(XML) 
require(httr) 
doc <- htmlTreeParse("http://www.cottonbledsoe.com/CM/Custom/TOCContactUs.asp", useInternal = TRUE) 
(string <- xpathSApply(doc, "substring-before(//div[@id = 'contactInformation']//p, 'Phone')", xmlValue, trim = TRUE)) 


require(RCurl) 
fetch <- GET("http://www.cottonbledsoe.com/CM/Custom/TOCContactUs.asp") 
contents <- content(fetch) 
locsnodes <- getNodeSet(contents, "//div[@id = 'contactInformation']//p") 
sapply(locsnodes, xmlValue) 

[1] "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n Phone: 432-897-1440\r\n Toll Free: 866-721-6665\r\n Fax: 432-682-3672" 

上面的代码工作确定,但我想用串 - 前清理的结果是这样的:

[1] "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n " 

locsnodes <- getNodeSet(contents, "substring-before(//div[@id = 'contactInformation']//p, 'Phone')") 
sapply(locsnodes, xmlValue) 

Error in UseMethod("xmlValue") : 
    no applicable method for 'xmlValue' applied to an object of class "character" 

如何使用substring-也RCurl,因为RCurl是选择软件包以便稍后使用更复杂的操作?

谢谢你的任何指导意见(或更好的方法来达到我想要的

+0

你可能只是做一个'xpathSApply(内容,“串 - 前(// DIV [@id =“contactInformation '] // p,'Phone')“,xmlValue,trim = TRUE)' – hrbrmstr 2014-10-05 13:12:32

+0

函数调用在这里是多余的,所以'doc [”substring-before(// div [@id ='contactInformation'] // p, '电话')“]'会做的伎俩。 – jdharrison 2014-10-05 13:20:07

+0

你不在任何地方使用httr? – hadley 2014-10-09 11:43:41

回答

3

xpathSApply或确实getNodeSetfun参数只称为如果返回节点集。在你的情况下被返回的字符串和该功能被忽略了:

xpathSApply

> xpathSApply(doc, "substring-before(//div[@id = 'contactInformation']//p, 'Phone')" 
+    , function(x){1} 
+) 
[1] "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n " 
require(XML) 
require(RCurl) 
doc <- htmlParse("http://www.cottonbledsoe.com/CM/Custom/TOCContactUs.asp") 
locsnodes <- getNodeSet(doc 
         , "substring-before(//div[@id = 'contactInformation']//p, 'Phone')") 
> locsnodes 
[1] "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n " 

> str(locsnodes) 
chr "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n " 

fun参数没有被这里使用

由于您的xpath未返回节点集。

1

下面是使用 rvest包的稍微不同的方法。我认为你是一般 最好做字符串操作中R,而不是 的XPath

library(rvest) 

contact <- html("http://www.cottonbledsoe.com/CM/Custom/TOCContactUs.asp") 

contact %>% 
    html_node("#contactInformation p") %>% 
    html_text() %>% 
    gsub(" Phone.*", "", .) 
#> [1] "500 West Illinois, Suite 300\r\n Midland, Texas 79701\r\n" 
+0

如果可能的话,会同意避免xpath中的字符串操作是明智的。 – jdharrison 2014-10-09 12:17:01

相关问题