使用 requests_html 随机抓取无来自 JS 站点的结果时间问题?

问题描述

我想从 IMDb 中抓取数据。由于beautifulsoup4 不能使用JavaScript,我使用html_request。 但是,我的代码随机给出(否)结果。当我重复相同的代码 10 次时,有时它会起作用,有时却不起作用。 time.sleep() 没有帮助(我想也许 JS 需要更长的时间来加载)。 为什么会这样以及如何解决

# from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://www.imdb.com/title/tt4236770/')
# time.sleep(1)
rating_show = r.html.find('.AggregateratingButton__ratingscore-sc-1il8omz-1')[0] # either works or 'list index out of range' error
rating_show = float(rating_show.text)
rating_show

解决方法

这是因为页面的类和结构正在发生变化以避免抓取。这不是由于 javascript 渲染造成的。

顺便说一下,如果你想渲染页面,你需要在 get 请求之后使用渲染方法 r.html.render()

在这里你可以绕过这个类以获得这样的电影符号:

from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://www.imdb.com/title/tt4236770/')

body = r.html.text
indice = body.find('/10')

print(body[indice - 3: indice])

# output: Always return '8.6'