Webhose.io和R - 来自API的多个查询

时间:2017-09-27 01:28:32

标签: r api loops jsonlite webhose

使用Webhose API提取数据,但每次调用只会返回100条记录,之后Webhose会以列的形式提供下一个URL,以便在您拥有所有数据之前调用下一个100。以下是我到目前为止的内容

**在我的情况下,我有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加入到一个名为combo

的数据帧中

任何人都对如何有效地做到这一点有任何想法?

1 个答案:

答案 0 :(得分: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可能需要更多参数。如果我得到一些备用周期,我将为整个REST API提供一个pkg包装器(如果/当我这样做时,我会回到这里)。

现在,可以从潜在的icky中创建好的列名:

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迭代的事情。

<强>更新

现在,您可以使用https://github.com/hrbrmstr/webhose中的2个功能。您需要这样做才能安装它,直到它在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的其余部分之前,我还需要一段时间。