【问题标题】:How to get rid of the error while scraping web in R?在R中抓取网页时如何摆脱错误?
【发布时间】:2020-12-11 20:34:22
【问题描述】:

我正在抓取 this 网站并收到一条错误消息,即 tibble 列必须具有兼容的大小。
这种情况我该怎么办?

library(rvest)
library(tidyverse)

url <- "https://www.zomato.com/tr/toronto/drinks-and-nightlife?page=5"
map_dfr(
  .x = url,
  .f = function(x) {
    tibble(
      url = x,
      place = read_html(x) %>%
        html_nodes("a.result-title.hover_feedback.zred.bold.ln24.fontsize0") %>%
        html_attr("title"),
      price = read_html(x) %>%
        html_nodes("div.res-cost.clearfix span.col-s-11.col-m-12.pl0") %>%
        html_text()
    )
  }
) -> df_zomato

提前致谢。

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    问题是由于每家餐厅都没有完整的记录。在此示例中,列表中的第 13 项不包括价格,因此价格向量有 14 项,而位置向量有 15 项。

    解决此问题的一种方法是找到公共父节点,然后使用html_node() 函数解析这些节点。 html_node() 将始终返回一个值,即使它是 NA。

    library(rvest)
    library(dplyr)
    library(tibble)
    
    
    url <- "https://www.zomato.com/tr/toronto/drinks-and-nightlife?page=5"
    readpage <- function(url){
       #read the page once
       page <-read_html(url)
    
       #parse out the parent nodes
       results <- page %>% html_nodes("article.search-result")
    
       #retrieve the place and price from each parent
       place <- results %>% html_node("a.result-title.hover_feedback.zred.bold.ln24.fontsize0") %>%
          html_attr("title")
       price <- results %>% html_node("div.res-cost.clearfix span.col-s-11.col-m-12.pl0") %>%
          html_text()
    
       #return a tibble/data,frame
       tibble(url, place, price)
    }
    
    readpage(url)
    

    还请注意,在上面的代码示例中,您多次阅读同一页面。这很慢并且会给服务器带来额外的负载。这可以被视为“拒绝服务”攻击。
    最好将页面读入内存一次,然后使用该副本。

    更新
    回答您关于多页的问题。将上述函数包装在lapply 函数中,然后绑定返回的数据帧(或小标题)列表

    dfs <- lapply(listofurls, function(url){ readpage(url)})
    finalanswer <- bind_rows(dfs)
    

    【讨论】:

    • 顺便说一句,当有两个或多个页面时我该怎么办?例如。 ?页=6。没有节点它就无法工作。
    • @nerdakgul,查看更新功能和底部注释。
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多