【问题标题】:How to scrape star ratings using Selenium or Beautifulsoup in Python?如何在 Python 中使用 Selenium 或 Beautifulsoup 来获取星级评分?
【发布时间】:2021-05-27 18:36:17
【问题描述】:

我正在尝试根据星级来获取评分。星星有不同的颜色,可以在 Chrome 中区分。但是,标签中的星星都是一样的。有没有办法根据星星的颜色刮取每个子类别的评分,例如,工作/生活平衡应该有 3 分。

网页可以在这里找到:https://www.glassdoor.ca/Reviews/Employee-Review-AAR-RVW40036525.htm


【问题讨论】:

  • 我看了一下网页源码,好像是用 JavaScript 来改变 span 元素的颜色,也就是说用 selenium 很难刮。
  • 谢谢。答案可能在类名中。
  • 您只想要 3 星下拉菜单下的评分吗?还是所有其他下拉菜单?
  • 所有其他人。它们可以以相同的方式完成。似乎星星的 div 标签的每个类名都对应一个从 1 到 5 的值。
  • 是的,我会的。仍在测试代码。

标签: python selenium beautifulsoup


【解决方案1】:

为了区分评级,每个评级类别的类别名称都不同。这是一个基于等级的所有类名的示例,值是类名。这可以让你从你需要的开始

{
"one_star" : "css-152xdkl",
"two_star" : "css-19o85uz",
"three_star" : "css-1ihykkv",
"four_star" : "css-1c07csa",
"five_star" : "css-1dc0bv4",
}

【讨论】:

    【解决方案2】:

    这就是我所做的。我主要使用 BeautifulSoup,因为我觉得它更舒服。

    # Find all the reviews on the page
    reviews = driver.find_elements_by_class_name('gdReview')
    
    # I used BeautifulSoup to collect the ratings
    for review in reviews:
        # Convert the Selenium element for a review into a BeautifulSoup object
        review_source = review.get_attribute('innerHTML')
        soup = BeautifulSoup(review_source, 'lxml')
    
        # Find the sub-ratings tag
        sub_ratings_tag = soup.find("div", {"class": "tooltipContainer"})
        # Find all the "li" tags
        li_tags = sub_ratings_tag.find_all("li")
    
        # Loop over each "li" tag and collect the ratings
        star_dict = {"css-152xdkl": 1, "css-19o85uz": 2, "css-1ihykkv": 3,
                     "css-1c07csa": 4, "css-1dc0bv4": 5}
        sub_rating_dict = {}
        for li_tag in li_tags:
            div_tags = li_tag.find_all("div")
            for div_tag in div_tags:                
                # Get the classname and the rating name
                if div_tag.has_attr("class"):
                    div_class=div_tag["class"][0]
                else:
                    sub_cat = div_tag.text.strip()
            star_value = star_dict[div_class]
            sub_rating_dict[sub_cat] = star_value
    

    【讨论】:

    • 不需要使用 Selenium,只需添加 user-agent 标头即可。看我的回答here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多