2014-10-05 12 views
0

식에서 XPath 1.0의 하위 문자열 - 또는 -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" 

위의 코드는 확인을 작동하지만 나는이 같은 결과를 정리하기 전에 문자열을-사용하려면 : 나는 substring-도 RCurl 사용 방법

[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" 

을 RCurl가 있기 때문에 나중에 사용되는 더 복잡한 작업을 위해 선택된 패키지?

내가 원하는 것을 달성하기 위해 어떤 지침 (또는 더 나은 방법을 주셔서 감사합니다

xpathSApply 또는 참으로 getNodeSetfun 인수 만이라고
+0

당신은'xpathSApply (내용 "문자열-전에 (// DIV을 바로 할 수보다는 XPath는보다, R에서 문자열 조작을하고 일반적으로 더 나을 을 것 같아요 [@id = 'contactInformation '); // xmlValue, trim = TRUE)' – hrbrmstr

+0

함수 호출이 여기에 중복되어 있으므로'doc [ "substring-before (// div [@id ='contactInformation '] // p, '전화') '' '이 트릭을 할 것입니다. – jdharrison

+0

어디서나 httr을 사용하지 않습니까? – hadley

답변

3

노드 집합이 반환되는 경우. 귀하의 경우에는 문자열이 반환되고 있으며, 기능은 무시됩니다 :

fun 인수가 여기에 사용하지 않을
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 " 

> 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 " 

xpath가 노드 집합을 반환하지 않으므로.

1

rvest 패키지를 사용하는 방식이 약간 다릅니다. 난 당신이

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