R:使用循环解析 html 文件组

R: Parsing group of html files with loop

以下代码适用于单个 .html 文件:

doc <- htmlParse("New folder/1-4.html")
plain.text <- xpathSApply(doc, "//td", xmlValue)
plain.text <- gsub("\n", "", plain.text)
gregexpr("firstThing", plain.text)
firstThing <- substring(plain.text[9], 41, 50)
gregexpr(secondThing, plain.text)
secondThing <- substring(plain.text[7], 1, 550)

但是下面的循环并没有给我错误:

XML内容好像不是XML

file.names <-  dir(path = "New folder")

for(i in 1:length(file.names)){
doc <- htmlParse(file.names[i])
plain.text <- xpathSApply(doc, "//td", xmlValue)
gsub("\n", "", plain.text)
firstThing[i] <- substring(plain.text[9], 41, 50)
secondThing[i] <- substring(plain.text[7], 1, 550)
  }

我只是想提取信息(正如我在第一批代码中所做的那样),并创建一个信息向量。

关于如何解决这个问题有什么想法吗?

两件事。首先,你的路径是错误的。要解决此问题,请使用:

filenames = dir(path = "New folder", full.names = TRUE)

其次,比在 for 循环中填充两个变量更好的方法是在列表函数中生成结构化数据:

result = lapply(filenames, function (filename) {
    doc = htmlParse(filename)
    plain_text = xpathSApply(doc, "//td", xmlValue)
    c(first = substring(plain_text[9], 41, 50),
      second = substring(plain_text[7], 1, 550))
})

现在 result 是一个元素列表,其中每个元素都是一个向量,名称为 firstsecond

其他几点说明:

  • 注意变量名中的点 - S3 使用名称中的点来确定泛型方法的 class。在变量名中使用点号会引起混淆,应该避免。

  • 循环中的 gsub 语句无效。