【发布时间】: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