0

式で XPath 1.0 の substring-before または -after を使用すると、後続の xmlValue 呼び出しでエラーが発生します。以下のコードは、XPath 式が httr では正常に機能するが、RCurl では機能しないことを示しています。

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-before を使用して、次のように結果をクリーンアップしたいと考えています。

[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を使用するにはどうすればよいですか?

ガイダンスに感謝します(または、私が望むものを達成するためのより良い方法

4

2 に答える 2

3

or Indeedのfun引数は、ノード セットが返された場合にのみ呼び出されます。あなたの場合、文字列が返され、関数は無視されます:xpathSApplygetNodeSet

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引数はここでは使用されていません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 "

xpath がノード セットを返さないためです。

于 2014-10-05T13:01:36.503 に答える
1

rvestパッケージを使用した、少し異なるアプローチを次に 示します。一般的には、xpath ではなく R で文字列操作を行うほうがよいと思います

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"
于 2014-10-09T11:48:32.767 に答える