R 无法抓取新闻网站
我正在从以下新闻提要rss创建一个数据集 我正在从这个xml中读取以下数据R 无法抓取新闻网站,r,web-scraping,R,Web Scraping,我正在从以下新闻提要rss创建一个数据集 我正在从这个xml中读取以下数据 头衔 标题url 酒馆日期 我现在使用标题url来获取描述(概要,在主标题下面)——点击每个url并抓取数据 然而,我面临着描述向量长度(197)与其他向量长度(200)不匹配的问题。 因此,我无法创建数据帧 有人能帮忙吗?我怎样才能高效地获取数据 以下代码是可复制的 library("httr") library("RCurl") library("jsonlite") library("lubridate")
- 头衔
- 标题url
- 酒馆日期
library("httr")
library("RCurl")
library("jsonlite")
library("lubridate")
library("rvest")
library("XML")
library("stringr")
url = "http://indianexpress.com/section/india/feed/"
newstopics = getURL(url)
newsxml = xmlParse(newstopics)
title <- xpathApply(newsxml, "//item/title", xmlValue)
title <- unlist(title)
titleurl <- xpathSApply(newsxml, '//item/link', xmlValue)
pubdate <- xpathSApply(newsxml, '//item/pubDate', xmlValue)
t1 = Sys.time()
desc <- NULL
for (i in 1:length(titleurl)){
page = read_html(titleurl[i])
temp = html_text(html_nodes(page,'.synopsis'))
desc = c(desc,temp)
}
print(difftime(Sys.time(), t1, units = 'sec'))
desc = gsub("\n",' ',desc)
newsdata = data.frame(title,titleurl,desc,pubdate)
您可以执行以下操作:
library(tidyverse)
library(xml2)
library(rvest)
feed <- read_xml("http://indianexpress.com/section/india/feed/")
# helper function to extract information from the item node
item2vec <- function(item){
tibble(title = xml_text(xml_find_first(item, "./title")),
link = xml_text(xml_find_first(item, "./link")),
pubDate = xml_text(xml_find_first(item, "./pubDate")))
}
dat <- feed %>%
xml_find_all("//item") %>%
map_df(item2vec)
# The following takes a while
dat <- dat %>%
mutate(desc = map_chr(dat$link, ~read_html(.) %>% html_node('.synopsis') %>% html_text))
注意:要获取每个项目的所有信息,您可以使用:
dat <- feed %>%
xml_find_all("//item") %>%
map_df(~xml_children(.) %>% {set_names(xml_text(.), xml_name(.))} %>% t %>% as_tibble)
dat%
xml\u find\u all(“//项”)%%>%
map_df(~xml_子项(.)%%>%{set_名称(xml_文本(.),xml_名称(.)}%%>%t%%为可存储)
我认为问题与temp
在for
循环中没有为每次迭代返回值有关。尝试将desc
行替换为desc=c(desc,paste0(“,temp))
——尽管需要更优雅的错误处理。我检查了titleurl是否处处为空。我假设,由于每个url都是一个报纸链接,它们肯定会有一个副标题
> glimpse(dat)
Observations: 200
Variables: 4
$ title <chr> "Common man has no problem with note ban, says Santosh Gangwar", "Bombay High Court comes...
$ link <chr> "http://indianexpress.com/article/india/india-news-india/demonetisation-note-ban-cash-cru...
$ pubDate <chr> "Mon, 21 Nov 2016 20:04:21 +0000", "Mon, 21 Nov 2016 20:01:43 +0000", "Mon, 21 Nov 2016 1...
$ desc <chr> "MoS for Finance speaks to Indian Express in Bareilly, his Lok Sabha constituency.", "The...
dat <- feed %>%
xml_find_all("//item") %>%
map_df(~xml_children(.) %>% {set_names(xml_text(.), xml_name(.))} %>% t %>% as_tibble)