【问题标题】:How to scrape and count star rating using Selenium and Python?如何使用 Selenium 和 Python 抓取和计算星级?
【发布时间】:2021-02-15 19:41:19
【问题描述】:

我目前正在尝试在这个特定网站上抓取评论:https://shopee.sg/buyer/275295198/rating,但我无法找到一种使用 selenium 来抓取星级的方法,因为每颗星星都是自己的 svg。意识到填充星星和未填充星星之间存在一种模式:

这是我当前的代码,用于对填充的星星进行计数和求和,但似乎只返回 1:

    # Star rating
      star_ratings = product.find_elements_by_css_selector("[class='shopee-product-rating__rating']")
      stars = product.find_elements_by_css_selector("[class='shopee-svg-icon icon-rating-solid--active icon-rating-solid']")

      star_rate = 0
      for rating in star_ratings:
          #print(rating.get_attribute('svg'))
          if (product.find_elements_by_css_selector("[class='shopee-svg-icon icon-rating-solid--active icon-rating-solid']")) == stars:
              star_rates = star_rate + 1
              continue
      rating_csv.append(star_rates)
      print(star_rates)

【问题讨论】:

  • 我觉得如果你使用find_elements_by_class_name会更好

标签: python selenium web-scraping


【解决方案1】:

您可以简单地使用starslen() 来获取信息,而无需迭代结果和计数,如果它只涵盖活动的星星:

rating_csv.append(len(stars))

示例

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')
url = 'https://shopee.sg/buyer/208830993/rating'
driver.get(url)
time.sleep(5)

for rating in driver.find_elements_by_css_selector('.shopee-product-rating'):
    stars = rating.find_elements_by_css_selector('.icon-rating-solid')
    print(len(stars))
    
driver.close()

输出

4
5
5
5
5
5

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2021-04-03
    • 2020-01-10
    • 2022-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多