【问题标题】:Bad-case for parsing html table with R用 R 解析 html 表的坏情况
【发布时间】:2014-07-15 07:40:20
【问题描述】:

我在使用 R 中的 RCurl 和 XML 解析 html 表时遇到了问题。方法 readHTMLTable 返回表的 0 长度命名列表。

问题是readHTMLTable() 无法将解析结果识别为 HTML 表格,但它是一个。

这是一个R代码:

library("RCurl")
library("XML")

plant<-"APCHC"
market<-"MED"
product<-"GAP"
start_date<-"7.1.2014"
end_date<-"14.7.2014"

curl <- getCurlHandle()

url<-URLencode("http://www.kortes.com/index/nb/index.php")
headers <- c(
  'Accept' = '*/*',
  'x-requested-with' = 'XMLHttpRequest',
  'User-Agent' = 'Mozilla/4.0',
  'Content-Type' = 'application/x-www-form-urlencoded; charset=UTF-8',
  'Accept-Encoding' = 'gzip, deflate'
)
body<- paste("codex=getForTable&val1=",plant,"&val2=",market,"&val3=",product,"&date1=",start_date,"&date2=",end_date, sep="")
reader = basicTextGatherer()
hh = basicHeaderGatherer()
res = curlPerform(url=url, httpheader= headers, postfields=body,     writefunction=reader$update, headerfunction = hh$update, curl=curl, .encoding="UTF-8")


kortes<-readHTMLTable(reader$value())

>length(kortes)
>[1] 0

请告诉我哪种方法适合解决这个问题。 谢谢!

【问题讨论】:

  • 我无法运行您的示例代码,缺少一些对象...
  • 我再次运行了这段代码,没有错误或丢失对象...
  • 这样问题就解决了???
  • @Richie Cotton 升级了代码。

标签: r parsing html-table rcurl


【解决方案1】:

reader$value() 的内容只是tr 元素,而不是整个表。试试:

readHTMLTable(paste0("<table>", reader$value(), "</table>"))

【讨论】:

    【解决方案2】:

    使用 httr 可以大大简化你的生活:

    library("httr")
    library("XML")
    
    r <- POST(
      "http://www.kortes.com/index/nb/index.php",
      body = list(
        val1 = "APCHC", # plant
        val2 = "MED", # market
        val3 = "GAP", # product
        date1 = "7.1.2014", # start date
        date2 = "14.7.2014"
      )
    )
    stop_for_status(r)
    
    kortes <- readHTMLTable(content(r, encoding = "UTF-8"))
    length(kortes)
    #> [1] 4
    

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      相关资源
      最近更新 更多