在 R 中抓取网页时如何消除错误?
How to get rid of the error while scraping web in R?
我正在抓取 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
提前致谢。
问题是因为每家餐厅都没有完整的记录。在此示例中,列表中的第 13 项不包括价格,因此价格向量有 14 项,而地点向量有 15 项。
解决此问题的一种方法是找到公共父节点,然后使用 html_node()
函数解析这些节点。 html_node()
将始终 return 一个值,即使它是 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
函数中,然后绑定 returned 数据帧(或 tibbles)
的列表
dfs <- lapply(listofurls, function(url){ readpage(url)})
finalanswer <- bind_rows(dfs)
我正在抓取 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
提前致谢。
问题是因为每家餐厅都没有完整的记录。在此示例中,列表中的第 13 项不包括价格,因此价格向量有 14 项,而地点向量有 15 项。
解决此问题的一种方法是找到公共父节点,然后使用 html_node()
函数解析这些节点。 html_node()
将始终 return 一个值,即使它是 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
函数中,然后绑定 returned 数据帧(或 tibbles)
dfs <- lapply(listofurls, function(url){ readpage(url)})
finalanswer <- bind_rows(dfs)