【问题标题】:rvest Error in open.connection(x, "rb") : HTTP error 404open.connection(x, "rb") 中的 rvest 错误:HTTP 错误 404
【发布时间】:2019-05-25 19:41:39
【问题描述】:

我试图抓取一个网站以使用 rvest 和 purrr 从许多页面中提取数据。但每次我运行代码时,“open.connection(x, "rb") 中的错误:HTTP 错误 404。”出现。

url <- "http://books.toscrape.com/catalogue/page-%d"

map_df(1:10, function(i){ 
  
  page <- read_html(sprintf(url, i))
   cat(".")
  
  booksdf <- data.frame(safely( title <- html_nodes(page, "h3, #title") %>% html_text(),
                       price <- html_nodes(page, ".price_color") %>% html_text() %>% gsub("£", "", .),
                       rating <- html_nodes(page, ".star-rating") %>% html_attrs() %>% str_remove("star-rating") %>%str_replace_all(c("One" = "1", "Two" = "2", "Three" = "3", "Four" = "4", "Five" = "5")) %>%  as.numeric()
                       )
                      
  )
  
  
} 
)
Error in open.connection(x, "rb") : HTTP error 404.

【问题讨论】:

  • 这是一个 R 编码错误?
  • 404错误表示在服务器中找不到您请求的页面。我建议您检查以确保您正在构建正确的 URL。如果我在浏览器中转到http://books.toscrape.com/catalogue/page-2,我会收到一个 404 错误,就像 R 一样。您是否忘记在 URL 中添加“.html”部分
  • 感谢@MrFlick 成功了。但是当我运行代码时出现另一个错误“类型(模式)错误:缺少参数“模式”,没有默认值”我找不到任何丢失的参数(每个代码在 map_df 之外运行完美)。

标签: r rvest


【解决方案1】:

我们可以创建要抓取的 URL,然后使用 map_df 将数据帧绑定在一起。

library(tidyverse)
library(rvest)

url <- "http://books.toscrape.com/catalogue/page-"
pages <- paste0(url, 1:10, ".html")

map_df(pages, function(i){ 
     page <- read_html(i)
     data.frame(title = html_nodes(page, "h3, #title") %>% html_text(),
                price = html_nodes(page, ".price_color") %>% html_text() %>% 
                        gsub("£", "", .),
                rating = html_nodes(page, ".star-rating") %>% html_attrs() %>% 
                         str_remove("star-rating") %>%
                         str_replace_all(c("One" = "1", "Two" = "2", 
                         "Three" = "3", "Four" = "4", "Five" = "5")) %>%  
                          as.numeric())
})


#                                            title price rating
#1                               A Light in the ... 51.77      3
#2                               Tipping the Velvet 53.74      1
#3                                       Soumission 50.10      1
#4                                    Sharp Objects 47.82      4
#5                     Sapiens: A Brief History ... 54.23      5
#6                                  The Requiem Red 22.65      1
#7                     The Dirty Little Secrets ... 33.34      4
#8                          The Coming Woman: A ... 17.93      3
#.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2016-01-22
    • 2023-01-07
    • 2021-10-31
    • 2020-09-22
    相关资源
    最近更新 更多