R 更改 html 表单中的值并抓取网络数据
R to change the values in html form and scrape web data
我想从此页面抓取历史天气数据 http://www.weather.gov.sg/climate-historical-daily。
我正在使用此 link .
中给出的代码
但是,我无法获取数据可能是由于页面结构发生了变化。在上面的代码中,link pgform <-html_form(pgsession)[[3]]
用于更改表单的值。我找不到类似的表格。
url <- "http://www.weather.gov.sg/climate-historical-daily"
pgsession <- html_session(url)
pgsource <- read_html(url)
pgform <- html_form(pgsession)
我的结果
> pgform
[[1]]
<form> 'searchform' (GET http://www.weather.gov.sg/)
<button submit> '<unnamed>
<input text> 's':
由于该页面有一个 CSV 下载按钮并且它提供的链接遵循某种模式,因此您可以生成并下载一组 URL。您将需要一组电台 ID,您可以从下拉列表本身中获取这些 ID:
library(rvest)
page <- 'http://www.weather.gov.sg/climate-historical-daily' %>% read_html()
station_id <- page %>% html_nodes('button#cityname + ul a') %>%
html_attr('onclick') %>% # If you need names, grab the `href` attribute, too.
sub(".*'(.*)'.*", '\1', .)
然后可以将其与月份和年份一起放入 expand.grid
以生成所有必要的组合:
df <- expand.grid(station_id,
month = sprintf('%02d', 1:12),
year = 2014:2016)
(请注意,如果您需要 2017 年的数据,则需要单独构建这些数据,并且 rbind
以免构建尚未发生的月份。)
然后可以将这些组合paste0
编入网址:
urls <- paste0('http://www.weather.gov.sg/files/dailydata/DAILYDATA_',
df$station_id, '_', df$year, df$month, '.csv')
可以lapply
下载所有文件:
# Warning! This will download a lot of files! Make sure you're in a clean directory.
lapply(urls, function(url){download.file(url, basename(url), method = 'curl')})
我想从此页面抓取历史天气数据 http://www.weather.gov.sg/climate-historical-daily。
我正在使用此 link
但是,我无法获取数据可能是由于页面结构发生了变化。在上面的代码中,link pgform <-html_form(pgsession)[[3]]
用于更改表单的值。我找不到类似的表格。
url <- "http://www.weather.gov.sg/climate-historical-daily"
pgsession <- html_session(url)
pgsource <- read_html(url)
pgform <- html_form(pgsession)
我的结果
> pgform
[[1]]
<form> 'searchform' (GET http://www.weather.gov.sg/)
<button submit> '<unnamed>
<input text> 's':
由于该页面有一个 CSV 下载按钮并且它提供的链接遵循某种模式,因此您可以生成并下载一组 URL。您将需要一组电台 ID,您可以从下拉列表本身中获取这些 ID:
library(rvest)
page <- 'http://www.weather.gov.sg/climate-historical-daily' %>% read_html()
station_id <- page %>% html_nodes('button#cityname + ul a') %>%
html_attr('onclick') %>% # If you need names, grab the `href` attribute, too.
sub(".*'(.*)'.*", '\1', .)
然后可以将其与月份和年份一起放入 expand.grid
以生成所有必要的组合:
df <- expand.grid(station_id,
month = sprintf('%02d', 1:12),
year = 2014:2016)
(请注意,如果您需要 2017 年的数据,则需要单独构建这些数据,并且 rbind
以免构建尚未发生的月份。)
然后可以将这些组合paste0
编入网址:
urls <- paste0('http://www.weather.gov.sg/files/dailydata/DAILYDATA_',
df$station_id, '_', df$year, df$month, '.csv')
可以lapply
下载所有文件:
# Warning! This will download a lot of files! Make sure you're in a clean directory.
lapply(urls, function(url){download.file(url, basename(url), method = 'curl')})