API New York Times с R - PullRequest
       0

API New York Times с R

0 голосов
/ 17 марта 2020

Я пытаюсь получить информацию о статьях, используя API New York Times. Файл CSV, который я получаю, не отражает мой запрос фильтра. Например, я ограничил источник «The New York Times», но полученный файл содержит и другие источники. Я хотел бы спросить вас, почему запрос фильтра не работает.

Вот код.

if (!require("jsonlite")) install.packages("jsonlite")
library(jsonlite)

api = "apikey"

nytime = function () {
  url = paste('http://api.nytimes.com/svc/search/v2/articlesearch.json?',
              '&fq=source:',("The New York Times"),'AND type_of_material:',("News"),
              'AND persons:',("Trump, Donald J"),
              '&begin_date=','20160522&end_date=','20161107&api-key=',api,sep="")
  #get the total number of search results
  initialsearch = fromJSON(url,flatten = T)
  maxPages = round((initialsearch$response$meta$hits / 10)-1)

  #try with the max page limit at 10
  maxPages = ifelse(maxPages >= 10, 10, maxPages)

  #creat a empty data frame
  df = data.frame(id=as.numeric(),source=character(),type_of_material=character(),
                  web_url=character())

  #save search results into data frame
  for(i in 0:maxPages){
    #get the search results of each page
    nytSearch = fromJSON(paste0(url, "&page=", i), flatten = T) 
    temp = data.frame(id=1:nrow(nytSearch$response$docs),
                      source = nytSearch$response$docs$source, 
                      type_of_material = nytSearch$response$docs$type_of_material,
                      web_url=nytSearch$response$docs$web_url)
    df=rbind(df,temp)
    Sys.sleep(5) #sleep for 5 second
  }
  return(df)
}

dt = nytime()
write.csv(dt, "trump.csv")

Вот файл CSV, который я получил. enter image description here

1 Ответ

1 голос
/ 17 марта 2020

Кажется, вам нужно поставить () внутри кавычек, а не снаружи. Как это:

  url = paste('http://api.nytimes.com/svc/search/v2/articlesearch.json?',
              '&fq=source:',"(The New York Times)",'AND type_of_material:',"(News)",
              'AND persons:',"(Trump, Donald J)",
              '&begin_date=','20160522&end_date=','20161107&api-key=',api,sep="")

https://developer.nytimes.com/docs/articlesearch-product/1/overview

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...