【问题标题】:missing class while webscraping -having difficulty in making a data.frame网页抓取时缺课 - 制作 data.frame 有困难
【发布时间】:2018-06-08 06:15:36
【问题描述】:

我正在“zomato.com”上开展一个项目,该项目向我们展示了世界各地的餐厅。它向我们展示了菜单、声誉、照片和其他许多信息。

我们要抓取墨尔本餐厅的“名称、评分投票、地址、美食、价格”的所有信息。

我们可以在'https://www.zomato.com/melbourne/restaurants'上对这些信息进行罚款

但是我们在通过整合上述所有 5 个变量来制作数据框时遇到了问题。原因是变量“价格”的某些结果没有值(其他 5 个变量每个有 150 个值,但价格有 144 个值)。

我们应该统一每个变量的结果数量以整合为一个数据框。我们需要做这一步,因为我们要用excel来分析爬取的结果。我们想将NA值赋予没有任何结果的值(价格省略的6个值)

你能给我一个答案吗,我如何给出 NA 值来生成所有变量 在数据框中

这是我们的代码。

install.packages("rvest")
install.packages("dplyr")
install.packages("writexl")
install.packages("stringr")
install.packages("data.table")
install.packages("tidyr")



library("rvest")
library("dplyr")
library("writexl")
library("stringr")
library("data.table")
library("tidyr")



#url
url <- "https://www.zomato.com/melbourne/restaurants?page="
page <- c(1:941)
zomato_url <- c()


for (i in 1:941){
  zomato_url[i] <- paste0(url,page[i])
}


#variable tp collect
name <- c()
rating_vote <- c()
address <- c()
cuisine <- c()
price <- c()


for(i in 1:10){
  html <- read_html(zomato_url[i])
  name <- c(name, html_nodes(html, ".result-        
            title.hover_feedback.zred.bold.ln24.fontsize0")%>%
            html_text(trim=T))
  rating_vote <- c(rating_vote, html_nodes(html, ".ta-                
                   right.floating.search_result_rating.col-s-4.clearfix")%>%
                   html_text(trim=T))
  address <- c(address, html_nodes(html, ".col-m-16.search-result- 
               address.grey-text.nowrap.ln22")%>%
               html_text(trim=T))
  cuisine <- c(cuisine, html_nodes(html, ".col-s-11.col-m-12.nowrap.pl0")%>%
               html_text(trim=T))
  price <- c(price, html_nodes(html, ".res- 
             cost.clearfix")%>%html_nodes(".col-s-11.col-m-12.pl0")%>%
             html_text(trim=T))
  print(i)
}



#making data frame
outcome <- data.frame(name, rating_vote, address, cuisine, price)


#importing to excel
write_xlsx(outcome, path="C:/Users/helen.DESKTOP- 
          SG9LJPT/Desktop/outcome.xlsx")

【问题讨论】:

  • 您是否尝试过按照here 的描述实现html_table(fill=TRUE)
  • 你能给我任何没有提到价格的链接吗?这可能是因为不同的 html 节点。尝试使用 xpath 并检查是否得到相同的值。
  • zomato.com/melbourne/restaurants?page=3 这是可以找到未提及价格的节点的链接!!谢谢你的帮助!

标签: r dataframe web-scraping web-crawler


【解决方案1】:

在报废前只使用一个条件。

使用标题 html 节点之后的条件。如果标题节点下的价格节点可用,则报废并放入列表中,然后将其附加到数据框中。

你也可以使用xpath,如果你使用xpath会更容易检查条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2020-05-04
    • 1970-01-01
    • 2020-11-10
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多