Search code examples
rubyseleniumwatir

How to scrape star ratings displayed as an image set as a background URL?


There are some websites that display different star ratings based on a single image set as background, for example: https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000004gHhLEAU

background: url(https://appexchange.salesforce.com/resource/1656544481000/assetsappx/images/appx-rating-stars.png) no-repeat 0 0;

How to scrape such rating values using Watir?


Solution

  • As @spickermann mentioned in the comments, the display of the rating image is controlled by the CSS classes. For example, the following has a "appx-rating-stars-45" class that creates the 4.5 star appearance:

    <span id="appxListingDetailPageId:AppxLayout:j_id841:j_id842:j_id845" class="appx-rating-stars appx-rating-stars-45"></span>
    

    To determine the star rating, we can retrieve this class and then parse the number:

    star_rating_element = browser.div(class: 'appx-listing-detail').span(class: 'appx-rating-stars')
    star_rating_raw = star_rating_element.class_name[/appx-rating-stars-(\d\d)/, 1]
    #=> "45"
    star_rating_value = star_rating_raw.to_i / 10.0
    #=> 4.5