获取 python 中执行的 javascript 内容

get the executed javascript content in python

有什么方法可以从网页中获取执行的javascript内容吗? 我已经尝试了请求 + BeautifulSoup、机械化,这些让我得到了网页的 "source code",而不是执行的 javascript。 例如,这个网站:- http://listen.tidal.com/login

如您所见,在源代码中,有未执行的 JS,但是,当您检查元素时,您会看到已执行的代码。

现在,有什么方法可以在 python 中获取已执行代码? 请提示,因为我已经尝试使用 mechanize 模拟浏览器并且它与 reuqests 一样。 谢谢

是的,您必须选择支持 Javascript 内容的工具,而不是机制。机制仅适用于您已经观察到的静态内容。有好几个,搜索词找到的"python alternative to mechanics"。如果我必须选择一个,我会测试 PhantomJS。

在评论中链接的其他答案中还发现了其他几个,只是为了避免 "SO is not a pick your favorite tool recommending site" 问题,我想将这些保留为评论,因此只提到了通用解决方案。所以,请搜索一下 ;)

其实执行javascript需要JavaScript engine。 Python 是一种语言,它有自己的解释器(编译器!)来执行 python 代码。这是两种不同的技术。因此,如果您想从 python 执行 javascript,python 必须具有 api 或与引擎交互的某种绑定执行 javascript。幸运的是 python 可以与多个 JS 引擎交互,以实现与 Web 相关的工作(测试等)。这个可互操作的 JS 可以分为以下两组-

  1. 浏览器没有图形用户界面(GUI)又名Headless browser: e.g. PhantomJS a Webkit rendering engine based headless browser, SlimerJS a Gecko rendering engine based headless browser for more see here. You can interoperate with PhantomJS with selenium ( a glue between python and PhantomJS) or you can use PyQt and use python to run JS like here
  2. 浏览器带有图形用户界面(GUI):例如Firefox、Chromium、Safari 等。在这种情况下,您也可以通过 selenium python.
  3. 执行 JS

JS在selenium中的简单执行示例python如下-

from selenium import webdriver
#define driver- firefox, chrome  or phantomjs etc.
driver = webdriver.Firefox()
#Open the url
driver.get('https://www.google.com')
#see how javascript simple alert is being executed
driver.execute_script("alert('hello world');")
#close the driver  i.e. closing opened Firefox instance!
driver.close()

只是强调 - Python 不会执行您的 Js 代码,但运行时会执行。 下面是 python 模块的示例,它会为您选择可用的运行时并评估代码。

Look at PyExecJS,您可以在此处找到一些示例,但请注意它可能不包含任何浏览器 API,例如 DOM、Html5 Api 等。它主要基于js引擎功能。

另一个大问题,python中的代码求值的原因是什么?