【问题标题】:Using "rvest" scraping html table使用“rvest”抓取 html 表
【发布时间】:2016-04-19 03:10:52
【问题描述】:

我尝试使用 rvest 包来刮一张桌子:

library(rvest)

x <- read_html ("http://www.jcb.jp/rate/usd04182016.html")
x %>% html_node(".CSVTable") %>% html_table 

Url 元素看起来像:

<table class="CSVTable">
 <tbody>...</tbody>
 <tbody class>...</tbody>
</table>

为什么会出现“无匹配”错误?

【问题讨论】:

  • 看看?html_table - "Parse an html table..."。然后试试x %&gt;% html_table。你看到你在页面上看到的表格无法被html_table解析

标签: html r web-scraping rvest


【解决方案1】:

你很幸运(有点)。该网站使用动态 XHR 请求来制作该表,但该请求也是一个 CSV 文件。

library(rvest)
library(stringr)

pg <- read_html("http://www.jcb.jp/rate/usd04182016.html")

# the <script> tag that does the dynamic loading is in position 6 of the 
# list of <script> tags

fil <- str_match(html_text(html_nodes(pg, "script")[6]), "(/uploads/[[:digit:]]+\\.csv)")[,2]

df <- read.csv(sprintf("http://www.jcb.jp%s", fil), header=FALSE, stringsAsFactors=FALSE)

df <- setNames(df[,3:6], c("buy", "mid", "sell", "symbol"))

head(df)
##        buy      mid     sell symbol
## 1   3.6735   3.6736   3.6737    AED
## 2  68.2700  69.0700  69.8700    AFN
## 3 122.3300 122.6300 122.9300    ALL
## 4 479.5000 481.0000 482.5000    AMD
## 5   1.7710   1.8110   1.8510    ANG
## 6 165.0600 165.3100 165.5600    AOA

但是,这也意味着您可以直接获取 CSV:

read.csv("http://www.jcb.jp/uploads/20160418.csv")

(只需在您的请求中正确格式化日期)。

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2020-04-19
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2020-10-15
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多