是否有更好的方法在R中执行此XML抓取任务?

时间:2011-12-12 19:51:30

标签: xml r xpath web-scraping

我有一些看起来像这样的XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
    <key>bbox.NE.lat</key>
    <string>-27.45433</string>
    <key>bbox.NE.lon</key>
    <string>153.01474</string>
    <key>bbox.SW.lat</key>
    <string>-27.45706</string>
    <key>bbox.SW.lon</key>
    <string>153.01239</string>
    <key>crs</key>
    <string>EPSG 4326</string>
    <key>found</key>
    <string>1</string>
</dict>
<array>
    <dict>
        <key>bbox</key>
        <dict>
            <key>bbox.NE.lat</key>
            <string>-27.45433</string>
            <key>bbox.NE.lon</key>
            <string>153.01474</string>
            <key>bbox.SW.lat</key>
            <string>-27.45706</string>
            <key>bbox.SW.lon</key>
            <string>153.01239</string>
        </dict>
        <key>centroid</key>
        <dict>
            <key>lat</key>
            <dict>
                <key>lat</key>
                <string>-27.45513</string>
                <key>lon</key>
                <string>153.0137</string>
            </dict>
        </dict>
        <key>id</key>
        <string>33037721</string>
        <key>properties</key>
        <dict>
            <key>amenity</key>
            <string>university</string>
            <key>name</key>
            <string>Queensland University of Technology</string>
            <key>osm_element</key>
            <string>way</string>
            <key>osm_id</key>
            <string>26303436</string>
        </dict>
    </dict>
</array>
</array>
</plist>

为了重现性,我用循环抓取了XML:

# initialize the vector
queries<-(0)
# loop over coordinates - signups$latlong is just a vector of coordinates
# signups$latlong[1] = "51.5130004883%20-0.1230000034 
# the space between lat & long is URL encoded
for(i in 1:length(signups$latlong)){
#self-imposed rate-limiting
Sys.sleep(0.05)
# if query returns an error, write NA and move on, also output to console so I can keep an eye on it
if(class(try(queries[i]<- getURL(paste("http://geocoding.cloudmade.com/[API KEY HERE]/geocoding/v2/find.plist?object_type=university&around=",signups$latlong[i],"&results=5&distance=closest", sep="")), silent=T))=="try-error")
  {
    queries[i]<-NA
    print("NA")
    print(i)
    }
  # just a progress indicator
  else(print(i))
}

我就在大学的名字之后。我对XML知之甚少,但我发现这很有用:

pagetree<-(0)
for (i in 1:length(queries)){
  plist<-xmlTreeParse(queries[i])$doc$children$plist
  nodes<-getNodeSet(plist, "//array//array//dict")
  if(class(try(pagetree[i]<-xmlValue(nodes[[5]][[4]]), silent = T))=="try-error") pagetree[i]<-NA
}

但是,我已经看到提到xmlXPathApply(),我想知道解析循环是否无法重写以使用它。

我被困的地方是我不知道如何为我想要的作品编写XPath,因为有多个节点具有相同的名称。

不要犹豫是否建议更好的方法来进行错误处理。

1 个答案:

答案 0 :(得分:3)

修复xml后......

使用xpath遍历此方法的方法是:

> plist = xmlParse('data.xml')
> xpathSApply(plist, '/plist/array/dict/dict/string', xmlValue)
[1] "-27.45433"                           "153.01474"                          
[3] "-27.45706"                           "153.01239"                          
[5] "university"                          "Queensland University of Technology"
[7] "way"                                 "26303436" 

您可以像平常一样索引输出。

但是,如果节点具有属性,例如<string type='uniname">...</string>,那么您可以使用漂亮的“@”语法,如:

> xpathSApply(plist, '/plist/array/dict/dict/string[@type='uniname']', xmlValue)

另一种方式,对于这种plist格式化可能更好,是:

> sapply(getNodeSet(plist, '//key[text() = "name"]'), function(x) xmlValue(getSibling(x)))
[1] "Queensland University of Technology"