2017-09-27 55 views
1

使用Webhose API提取数据,但是每次调用仅返回100条记录,之后Webhose以列的形式提供下一个URL以呼叫下一个100,直到您拥有全部的数据。下面是我迄今为止Webhose.io和R - 来自API的多个查询

**对我来说,我有200条记录这意味着我要运行它的2倍,以获取所有数据我找

#Pull the data from Webhose as JSON 
as_json<- f"http://webhose.io/filterWebContent?token=XXXb&format=json&ts=1213456&sort=crawled&q=(China%20AND%20United%20)%20language%3Aenglish%20site_type%3Anews%20site%3Abloomberg.com") 

#Convert the JSON into a DataFrame 
df_1 <- as.data.frame(as_json) 

#Subset the new URL which appears as column from the first pull 
next_url <- df_1$next.[1] 

#Pull data from Webhose as JSON using the new URL - to retrieve the next 100 
as_json2 <- fromJSON(next_url) 

#Convert the JSON into a DataFrame - 2nd Time 
df_2 <- as.data.frame(as_json2) 

我的问题是,需要迭代地做这件事,直到没有任何更多的呼叫。数据框中有名为moreResultsAvailable的列。当这个命中为零时,可以假定没有剩余的拉。我假设我们将使用此列来帮助关闭循环。我也不知道这可能需要多少次调用。

我当时想所有的DFS一起加入到所谓的组合

任何一个数据帧有任何想法,我怎么能有效地做到这一点?

回答

1

您需要使用一些弯头润滑脂并连接必要的样板位以遍历所需的响应数。

一些软件包,我们需要:

library(httr) 
library(jsonlite) 
library(tidyverse) 

创建CPL功能将让生活更轻松。

首先,一个用于请求内容:

filter_web_content <- function(query, sort = "relevancy", 
           ts = (Sys.time() - (3 * 24 * 60 * 60)), 
           order = "asc", size = 100, from = 0, 
           token = Sys.getenv("WEBHOSE_TOKEN")) { 

    params <- list(
    token = token, 
    format = "json", 
    q = query, 
    sort = sort, 
    order = order, 
    size = size, 
    ts = ts 
) 

    httr::GET(
    url = "https://webhose.io/filterWebContent", 
    query = params 
) -> res 

    httr::stop_for_status(res) 

    res <- httr::content(res, as = "text", encoding = "UTF-8") 
    res <- jsonlite::fromJSON(res, flatten = TRUE) 

    res 

} 

他们对这个特定端点REST API可以多走几家PARAMS。如果我得到一些备用周期,我将为这整个REST API抽取一个pkg包装器(如果/当我这样做时,我会回到这里)。现在

,一个从潜在的恶心的人做很好的列名:

mcga <- function(tbl) { 

    x <- colnames(tbl) 
    x <- tolower(x) 
    x <- gsub("[[:punct:][:space:]]+", "_", x) 
    x <- gsub("_+", "_", x) 
    x <- gsub("(^_|_$)", "", x) 
    x <- make.unique(x, sep = "_") 

    colnames(tbl) <- x 

    tbl 

} 

这里的设置位:

  • 预分配列表,以避免越来越多&复制。我不知道,如果“30”是该API
  • 创建一个循环,增加这两个列表索引变量和API获取起始位置
  • 推,结果到下一个空插槽列表中的一个很好的默认

之后我们会用数据做一些事情。

PRE_ALLOC_MAX <- 30 
results <- vector(mode = "list", length = PRE_ALLOC_MAX) 

i <- 1 
from <- 0 
repeat { 
    res <- filter_web_content("(China AND United) language:english site_type:news site:bloomberg.com", 
          ts = 1213456, from = from) 
    results[[i]] <- res 
    if (res[["moreResultsAvailable"]] > 0) { 
    message("Fetching next 100 records...") 
    i <- i + 1 
    from <- from + 100 
    } else { 
    break 
    } 
} 
## Fetching next 100 records... 
## Fetching next 100 records... 

目前:

  • 除去任何NULL(空置)条目
  • 与数据提取API结果的一部分,我们需要
  • 包起来在数据帧
  • 使列名重新变大

你不需要做这种方式,但我认为这是从长远来看更具有可读性:

discard(results, is.null) %>% 
    map_df(~{ .x$posts}) %>% 
    tbl_df() %>% 
    mcga() 
## # A tibble: 227 x 42 
##          uuid 
##          <chr> 
## 1 ea6f6084be16a50b0d4791ffa268956ca691c16d 
## 2 bd0ac60981ac73e2a7e71378881272eb5b6147d7 
## 3 3f2c2c13aa2b3c6d5fc8300f3a9876d9c86c08d1 
## 4 659d73d3ddba3c0a0505da8fc15862bc33ac9519 
## 5 371293cf38efe9c9a4708403c816c8b33eeb1298 
## 6 38a3522fe1d268519aa0e2c3c865bbee19f9ee65 
## 7 a4b1f0e4a8d94354ae41c80bebe56237b5a39ca8 
## 8 323660c1c21662a1e5b147455f7a4c70f60e12b8 
## 9 3233102dbbed6bd90c19ddb2cf7df9111de6ffcf 
## 10 c4f126943968be899a6c5fdd806274f0ca848714 
## # ... with 217 more rows, and 41 more variables: url <chr>, ord_in_thread <int>, 
## # author <chr>, published <chr>, title <chr>, text <chr>, highlighttext <chr>, 
## # highlighttitle <chr>, language <chr>, external_links <list>, rating <lgl>, 
## # crawled <chr>, thread_uuid <chr>, thread_url <chr>, thread_site_full <chr>, 
## # thread_site <chr>, thread_site_section <chr>, thread_site_categories <list>, 
## # thread_section_title <chr>, thread_title <chr>, thread_title_full <chr>, 
## # thread_published <chr>, thread_replies_count <int>, 
## # thread_participants_count <int>, thread_site_type <chr>, thread_country <chr>, 
## # thread_spam_score <dbl>, thread_main_image <chr>, 
## # thread_performance_score <int>, thread_domain_rank <int>, 
## # thread_social_facebook_likes <int>, thread_social_facebook_comments <int>, 
## # thread_social_facebook_shares <int>, thread_social_gplus_shares <int>, 
## # thread_social_pinterest_shares <int>, thread_social_linkedin_shares <int>, 
## # thread_social_stumbledupon_shares <int>, thread_social_vk_shares <int>, 
## # entities_persons <list>, entities_organizations <list>, 
## # entities_locations <list> 

考虑周围的rOpenSci GitHub的源戳的API包。他们中的一些人有类似的习惯做这种类型的API迭代的东西。

UPDATE

您现在可以使用2个功能https://github.com/hrbrmstr/webhose这一点。你需要做安装它,直到它在CRAN:

devtools::install_github("hrbrmstr/webhose") 

如果你想处理你自己的分页或只查询一个结果集,然后做

res <- webhose::filter_web_content("(China AND United) language:english site_type:news site:bloomberg.com", ts = 1213456) 

如果你想自动API分页,然后:

res <- webhose::fetchall_web_content("(China AND United) language:english site_type:news site:bloomberg.com", ts = 1213456) 

我会过一段时间,然后再覆盖其余的API。