【问题标题】:Scraping JavaScript page with python requests and asyncio in Jupyter notebook在 Jupyter 笔记本中使用 python 请求和 asyncio 抓取 JavaScript 页面
【发布时间】:2020-02-24 08:19:44
【问题描述】:

这与 this 问题的重复相去甚远,因为该问题甚至不使用抓取请求,而仅用于会话和获取页面内容。我也以这种方式与 Beautiful Soup 一起使用它。

我也试过this。但他们也没有解释如何有效地使用请求来获取 JavaScript 内容。

我正在尝试从由 JavaScript 代码呈现的网页中抓取信息。我在 Jupyter notebook 中使用 requests 模块。

当我使用以下示例代码时:

import asyncio
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()

r = await asession.get('http://python-requests.org')
r.html.render()
r.html.search('Python 2 will retire in only {months} months!')['months']

我得到错误:

RuntimeError: 这个事件循环已经在运行

我需要一些关于如何实现此comment 的建议,以使其在我输入 Jupyter 笔记本时开始工作:

asyncio.get_event_loop()

我明白了:

<_windowsselectoreventloop>running=True closed=False debug=False>

所以我需要在 Jupyter notebook 中使用现有循环的方法。

【问题讨论】:

标签: python-3.x asynchronous jupyter-notebook python-asyncio


【解决方案1】:

我对 asyncio 不太熟悉,但我相信如果你使用 AsyncHTMLSession

,你应该等待你的函数
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()

async def get_results():
    r = await asession.get('http://python-requests.org')
    return r

a = asession.run(get_results)
print(a[0].html.search('Python 2 will retire in only {months} months!')) # return None because text is not present there

没有 AsyncHTMLSession

from requests_html import HTMLSession
session = HTMLSession()

r = session.get('http://python-requests.org')

r.html.render()

print(r.html.search('Python 2 will retire in only {months} months!')) # None

【讨论】:

猜你喜欢
  • 2019-05-25
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多