【问题标题】:How can I ensure a correct assignment of ratings to reviews when a rating is missing (webscraping IMDB, python)?当缺少评级(网络抓取 IMDB、python)时,如何确保将评级正确分配给评论?
【发布时间】:2021-08-15 10:19:05
【问题描述】:

我从 stackoverflow (link) 中的答案中修改了代码(见下文),除了评论的标题和内容外,还抓取了 IMDB 上的评级。

然而,当有评论但没有给出评级时,它会将评级分配给正确的评论。例如,如果索引为 3 的评论没有评分,则将为其分配下一个可用评分(另一个评论的)。这会导致错误的评分分配(评论索引和评分不匹配)。

如何确保将评分正确分配给评论?
例如,将缺失值分配给没有评分的评论。

任何帮助将不胜感激。

url = (
    "https://www.imdb.com/title/tt6320628/reviews/_ajax?ref_=undefined&paginationKey={}"
)
key = ""
data = {"title": [], "review": [], "rating": []}

while True:
    response = requests.get(url.format(key))
    soup = BeautifulSoup(response.content, "html.parser")
    # Find the pagination key
    pagination_key = soup.find("div", class_="load-more-data")
    if not pagination_key:
        break

    # Update the `key` variable in-order to scrape more reviews
    key = pagination_key["data-key"]
    for title, review, rating in zip(
        soup.find_all(class_="title"), soup.find_all(class_="text show-more__control"), soup.find_all(class_="rating-other-user-rating")
    ):
        data["title"].append(title.get_text(strip=True))
        data["review"].append(review.get_text())
        data["rating"].append(rating.get_text(strip=True))

df = pd.DataFrame(data)
print(df)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您可以使用此示例检查是否有评论评分。如果不是,则使用字符串N/A

    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    
    url = "https://www.imdb.com/title/tt6320628/reviews/_ajax?ref_=undefined&paginationKey={}"
    key = ""
    data = {"title": [], "review": [], "rating": []}
    
    while True:
        print(url.format(key))
        response = requests.get(url.format(key))
        soup = BeautifulSoup(response.content, "html.parser")
        # Find the pagination key
        pagination_key = soup.find("div", class_="load-more-data")
        if not pagination_key:
            break
    
        # Update the `key` variable in-order to scrape more reviews
        key = pagination_key["data-key"]
    
        for r in soup.select(".review-container"):
            title = r.find(class_="title")
            review = r.find(class_="text show-more__control")
            rating = r.find(class_="rating-other-user-rating")
    
            data["title"].append(title.get_text(strip=True))
            data["review"].append(review.get_text())
            data["rating"].append(rating.get_text(strip=True) if rating else "N/A")
    
    df = pd.DataFrame(data)
    print(df)
    df.to_csv("data.csv", index=False)
    

    保存data.csv(来自 LibreOffice 的屏幕截图):

    【讨论】:

    • 感谢您抽出宝贵时间帮助我!这完美解决了。
    猜你喜欢
    • 2014-09-10
    • 1970-01-01
    • 2016-03-16
    • 2022-01-18
    • 1970-01-01
    • 2014-10-28
    • 2015-11-18
    • 2020-07-07
    • 2016-05-12
    相关资源
    最近更新 更多