【问题标题】:Scrape Product Rating that is shown as %-width of five stars抓取显示为五颗星宽度百分比的产品评分
【发布时间】:2023-01-03 17:38:03
【问题描述】:

我想从页面https://www.gonser.ch/ 中抓取平均产品评级。 我看到评级显示为 5 颗可能的星星中有多少被填充的百分比宽度(金色)。 使用我的代码,我可以以某种方式提取一些宽度,但不完全是我想要的值:

page <- read_html("http://www.gonser.ch/13879")

# extract the div element
div_element <- html_nodes(page, ".feedback-stars-overlay-wrap") 

# Extract the "style" attribute from the element
style_attribute <- html_attr(div_element, "style") 

# extract the width value
width_value <- str_extract(style_attribute, "width: ([0-9.]+)%") 

# Convert to a numeric value
width <- as.numeric(width_value)

结果,我得到 style_attribute 的 9 个不同的值,其中 2 个是 NA,其他的不是我检查页面时看到的值(在这个例子中,此时它是 width: 91.6%邮政)

有谁知道如何正确提取平均星级的宽度? 非常感谢您!

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:
    library(tidyverse)
    library(rvest)
    
    "https://www.gonser.ch/13879/" %>%
      read_html() %>%
      html_elements(".feedback-stars-overlay-wrap") %>%
      html_attr("style") %>%
      str_remove_all("[^\.0-9]") %>%
      as.numeric() %>%
      na.omit() %>% 
      mean()
    
    [1] 95.51429
    

    【讨论】:

    • 谢谢您的回答。使用您的代码,我能够重现您的结果,但我无法将其应用于单个产品页面(例如 www.gonser.ch/13879)。它仍然会给我 9 个值,其中 2 个为 NA。据我所知,2 个 NA 是实际产品的平均评级,其他 7 个值来自下面的产品。我只需要实际产品的平均产品评级的宽度。您知道如何将您的代码应用于上述产品页面吗?
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 2013-09-26
    • 2011-04-20
    • 2018-07-06
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多