当我在表达式中使用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是选择软件包以便稍后使用更复杂的操作?
谢谢你的任何指导意见(或更好的方法来达到我想要的
你可能只是做一个'xpathSApply(内容,“串 - 前(// DIV [@id =“contactInformation '] // p,'Phone')“,xmlValue,trim = TRUE)' – hrbrmstr 2014-10-05 13:12:32
函数调用在这里是多余的,所以'doc [”substring-before(// div [@id ='contactInformation'] // p, '电话')“]'会做的伎俩。 – jdharrison 2014-10-05 13:20:07
你不在任何地方使用httr? – hadley 2014-10-09 11:43:41