没有适用于'xpathApply'的方法应用于类“NULL”的对象

时间:2014-04-01 18:48:08

标签: html regex r web-scraping last.fm

我有以下代码我不知道为什么会收到此错误:

rm(list=ls())
require("XML")
# <a href="/music/The+Beatles/Sgt.+Pepper%27s+Lonely+Hearts+Club+Band" 
beatles = "http://www.last.fm/music/The+Beatles/"

beatles.albums.page = paste(sep="", beatles, "+albums")
lines = readLines(beatles.albums.page)
album.lines = grep(pattern="href.*link-reference", lines, value=TRUE)
album.names = sub(pattern=".*<h3>(.*)</h3>.*", replacement="\\1", x=album.lines)
album.names = gsub(pattern=" ", replacement="+", x=album.names)
album.names = gsub(pattern="'", replacement="%27", x=album.names)

for (album in album.names[1]) {
  print(album)
  album.link = paste(sep="", beatles, album)
  print(album.link)
  tables = readHTMLTable(album.link)

}

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

该行

readHTMLTable(album.link)

导致错误。尝试将其更改为

tables = readHTMLTable(album.link, header = FALSE)

但它仍然会给你警告:

Warning message:
In readLines(beatles.albums.page) :
  incomplete final line found on 'http://www.last.fm/music/The+Beatles/+albums'

你可以摆脱

readLines(beatles.albums.page, warn = FALSE) 

另请注意,您没有“保存”表格,它会在每个循环中发生变化,但也许这就是您想要的。