【问题标题】:rvest to ignore urls don't exist and move on with scrapingrvest 忽略 url 不存在并继续抓取
【发布时间】:2020-09-01 00:45:44
【问题描述】:

我是网络抓取和 rvest 包的新手。我想要完成的是从以下网站中获取新闻内容:http://www.xwlbo.com/31035.html

我注意到数字索引有历史新闻的模式,但后来我发现数字索引是随机的,没有明确的规则,因此可能存在不存在的网页,我收到了 @987654322 的错误@。如何忽略空网页并继续使用确实存在的网页。

到目前为止,这是我想出的:

library(tidyverse)
library(lubridate)
library(stringr)
library(rvest)
Sys.setlocale(category="LC_ALL",locale="chinese")

web_index_number <- 4058:31106

urls <- str_c("http://www.xwlbo.com/",web_index_number,".html")



news_collect <- function(x){
  webpage <- read_html(x)
  wp_title <- html_node(webpage,'h2') %>% 
   html_text()
wp_content <- html_nodes(webpage,'p , a , h2') %>% 
   html_text()
len <- length(wp_content)-3
wp_content <- wp_content[1:len]
wp_title <- rep(wp_title,len)
news <- data.frame(wp_title,wp_content)}

news_collection <- map_df(urls,news_collect)

【问题讨论】:

    标签: web-scraping rvest


    【解决方案1】:

    您可以使用 trycatch 结构来尝试执行以 news_collect 开头的代码。如果 read_html(x) 失败,你可以只写错误代码来打印错误并返回 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-17
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2019-04-10
      • 2011-12-01
      • 1970-01-01
      相关资源
      最近更新 更多