首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法浏览新闻网站

无法浏览新闻网站
EN

Stack Overflow用户
提问于 2016-11-21 20:01:58
回答 1查看 102关注 0票数 2

我正在从以下新闻提要rss http://indianexpress.com/section/india/feed/创建一个数据集

我正在从这个xml读取以下数据

  • 标题
  • 标题url
  • 酒吧约会

我现在使用标题url来获取描述(概要,在主标题下面)-通过点击每个url并抓取数据。

然而,我正面临向量长度(197)与其他描述( 200)不匹配的问题。正因为如此,我无法创建我的数据文件。

有人能帮忙吗?我怎样才能有效地抓取数据?

下面的代码是可复制的

代码语言:javascript
复制
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)

我得到以下错误:

代码语言:javascript
复制
Error in data.frame(title, titleurl, desc, pubdate) : 
arguments imply differing number of rows: 200, 197
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-21 20:23:45

您可以执行以下操作:

代码语言:javascript
复制
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))

它为您提供了一个包含4列的data.frame/tibble

代码语言:javascript
复制
> 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...

P.S.:要获取每个item的所有信息,您可以使用:

代码语言:javascript
复制
dat <- feed %>% 
  xml_find_all("//item") %>% 
  map_df(~xml_children(.) %>% {set_names(xml_text(.), xml_name(.))} %>% t %>% as_tibble)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40728367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档