R 编程中的网页抓取 (rvest) [英] Web-Scraping in R programming (rvest)

查看:48
本文介绍了R 编程中的网页抓取 (rvest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试抓取所有详细信息(旅客类型、座位类型、路线、飞行日期、座位舒适度、机舱员工服务、食品和饮料、机上娱乐、地面服务、Wifi 和连接、价值For Money) 包括星级

I am trying to scrape all details (Type Of Traveller, Seat Type,Route,Date Flown, Seat Comfort, Cabin Staff Service, Food & Beverages, Inflight Entertainment,Ground Service,Wifi & Connectivity,Value For Money) inclusive of the star rating

来自航空公司质量网页

https://www.airlinequality.com/airline-reviews/emirates/

未按预期工作

my_url<- c("https://www.airlinequality.com/airline-reviews/emirates/")

review <- function(url){
    review<- read_html(url) %>%
    html_nodes(".review-value") %>%
    html_text%>%
    as_tibble()   
   }
output <- map_dfr(my_url, review )

只能刮星级,我需要所有详细信息(例如客舱员工服务 - 评级 2,食品和饮料 = 评级 5)

Only able to scrape star rating , I need to have the all details (e.g Cabin Staff Service - rating 2 , Food & Beverages = rating 5)

star <- function(url){ 
  stars_sq <- read_html(url) %>%
    html_nodes(".star") %>%
    html_attr("class") %>%
    as.factor() %>%
    as_tibble()
}

output_star<- map_dfr(my_url, star )

结果的输出应该是表格形式:

The output of the result should be in a table form :

:旅行者类型、座位类型、航线、飞行日期、座位舒适度......与星级
:每条评论

column : Type Of Traveller , Seat Type,Route,Date Flown, Seat Comfort .... with the star rating
row : each reviews

推荐答案

这有点复杂,因为您需要将已填充/未填充的星星列表以获取每个字段的评分.我会使用 html_table() 来帮助,然后重新插入计算出的星值:

It's a little involved because you need to tabulate the filled/unfilled stars to get the rating for each field. I would use html_table() to help, then re-insert the calculated star values:

require(tibble)
require(purrr)
require(rvest)

my_url <- c("https://www.airlinequality.com/airline-reviews/emirates/")

count_stars_in_cell <- function(cell)
{
  html_children(cell) %>% 
  html_attr("class")  %>%
  equals("star fill") %>% 
  which               %>% 
  length
}

get_ratings_each_review <- function(review) 
{
  review                             %>%
  html_nodes(".review-rating-stars") %>%
  lapply(count_stars_in_cell)        %>%
  unlist
}

all_tables <- read_html(my_url)      %>%
              html_nodes("table")

reviews <- lapply(all_tables, html_table)

ratings <- lapply(all_tables, get_ratings_each_review)

for (i in seq_along(reviews))
{
  reviews[[i]]$X2[reviews[[i]]$X2 == "12345"] <- ratings[[i]]
}

print(reviews)

这会为您提供一个列表,其中包含每个评论的一张表格.这些应该很容易组合成一个单一的数据框.

This gives you a list with one table for each review. These should be straightforward to combine into a single data frame.

这篇关于R 编程中的网页抓取 (rvest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆