我想从
this webpage下载数据
数据可以很容易地被掠夺.
代码可能是这样的:
library(rvest) library(pipeR) url <- "http://www.tradingeconomics.com/" css <- "#ctl00_ContentPlaceHolder1_defaultUC1_CurrencyMatrixAllCountries1_GridView1" data <- url %>>% html() %>>% html_nodes(css) %>>% html_table()
但是这样的网页有一个问题.
有一个按钮来显示所有国家的数据,但默认值仅为50个国家/地区的数据.
解决方法
有时最好在ajax网络请求级别攻击该问题.对于本网站,您可以使用Chrome的开发工具并观看请求.为了构建表格(整个表格),它使用各种ajax-y参数对站点进行POST.只要复制一下,做一些数据的响应,你很好去:
library(httr) library(rvest) library(dplyr) res <- POST("http://www.tradingeconomics.com/",encode="form",user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/42.0.2311.50 Safari/537.36"),add_headers(`Referer`="http://www.tradingeconomics.com/",`X-MicrosoftAjax`="Delta=true"),body=list( `ctl00$AjaxScriptManager1$ScriptManager1`="ctl00$ContentPlaceHolder1$defaultUC1$CurrencyMatrixAllCountries1$UpdatePanel1|ctl00$ContentPlaceHolder1$defaultUC1$CurrencyMatrixAllCountries1$LinkButton1",`__EVENTTARGET`="ctl00$ContentPlaceHolder1$defaultUC1$CurrencyMatrixAllCountries1$LinkButton1",`srch-term`="",`ctl00$ContentPlaceHolder1$defaultUC1$CurrencyMatrixAllCountries1$GridView1$ctl01$DropDownListCountry`="top",`ctl00$ContentPlaceHolder1$defaultUC1$CurrencyMatrixAllCountries1$ParameterContinent`="",`__ASYNCPOST`="false")) res_t <- content(res,as="text") res_h <- paste0(unlist(strsplit(res_t,"\r\n"))[-1],sep="",collapse="\n") css <- "#ctl00_ContentPlaceHolder1_defaultUC1_CurrencyMatrixAllCountries1_GridView1" tab <- html(res_h) %>% html_nodes(css) %>% html_table() tab[[1]]$COUNTRIESWORLDAMERICAEUROPEASIAAUSTRALIAAFRICA glimpse(tab[[1]]
另一个选择是使用RSelenium去页面,点击“”,然后刮掉结果表.