for循环 - 无法正常工作

时间:2017-06-09 14:24:02

标签: json r for-loop

我尝试使用Indeed API来搜索特定的作业,而且当for循环没有经历每次迭代时我遇到了问题。     以下是我使用的代码示例:

original_url_1 <- "http://api.indeed.com/ads/apisearch?publisher=750330686195873&format=json&q="
original_url_2 <-"&l=Canada&sort=date&radius=10&st=&jt=&start=0&limit=25&fromage=3&filter=&latlong=1&co=ca&chnl=&userip=69.46.99.196&useragent=Mozilla/%2F4.0%28Firefox%29&v=2" 
keywords <- c("data+scientist", "data+analyst")

for(i in keywords) { 
    url <- paste0(original_url_1,i,original_url_2)
    x <- as.data.frame(jsonlite::fromJSON(httr::content(httr::GET(url),
                                    as = "text", encoding = "UTF-8")))
     data <- rbind(data, x)
 }

Url会导致JSON文件,并且将一个关键字添加到url将更改JSON文件。因此,我尝试对所有关键字重复此操作,并将结果存储在数据框中。但是,当我尝试使用更多关键字时,我只会为少数第一个关键字获取结果。

2 个答案:

答案 0 :(得分:0)

 original_url_1 <- "http://api.indeed.com/ads/apisearch?publisher=750330686195873&format=json&q="
 original_url_2 <-"&l=Canada&sort=date&radius=10&st=&jt=&start=0&limit=25&fromage=3&filter=&latlong=1&co=ca&chnl=&userip=69.46.99.196&useragent=Mozilla/%2F4.0%28Firefox%29&v=2" 
 keywords <- c("data_scientist", "data+analyst")

 data<-data.table(NULL)#initialization of object

 for(i in keywords) { 
   url <- paste0(Original_url_1,i,Original_url_2)
   x <- as.data.frame(jsonlite::fromJSON(httr::content(httr::GET(url),as = "text", encoding = "UTF-8")))
   data <- rbind(data, x)
}

>dim(data)
[1] 39 31

答案 1 :(得分:0)

这是正确的代码:

original_url_1 <- "http://api.indeed.com/ads/apisearch?publisher=750330686195873&format=json&q="
original_url_2 <-"&l=Canada&sort=date&radius=10&st=&jt=&start=0&limit=25&fromage=3&filter=&latlong=1&co=ca&chnl=&userip=69.46.99.196&useragent=Mozilla/%2F4.0%28Firefox%29&v=2" 
keywords <- c("data+scientist", "data+analyst")

data <- data.frame()

for (i in keywords) {
  tryCatch({url <- paste0(original_url_1,i,original_url_2)
  x <- as.data.frame(jsonlite::fromJSON(httr::content(httr::GET(url),
                                                     as = "text", encoding = "UTF-8")))
  data <- rbind(data, x)
  }, error = function(t){})
}