从Python执行页面上的JS代码

问题描述 投票:0回答:2

我的任务是使用 Python 从任何网页获取命名函数的列表。

我有一个使用 JavaScript 编写的脚本。它满足我的需要。

加载页面后,我可以从 JS 控制台运行脚本(例如,从 GoogleChrome 中的开发工具)。我得到了函数名称数组作为结果。好吧,但我转到该页面并从浏览器手动执行脚本。但问题是在 Python 中做同样的事情。它可能看起来像这样:

def get_named_functions_list(url):
    myscript = settings.get_js_code()  # here I get script that I told above

    tool.open(url)

    while not tool.document.READY: # here I wait while the page will completely loaded
        pass

    js_result = tool.execute_from_console(myscript)

    return list(js_result.values())

那么,Python中有没有一个工具可以帮助自动解决问题呢?

更新: 为了更清楚,我可以将任务划分为子任务列表(在 Python 中):

  1. 请求给定的url
  2. 等待 document.ready(function...) 完成。
  3. 执行我的 JS 代码(就像在浏览器中一样)。
  4. 获取JS代码返回的结果。
javascript python python-3.x
2个回答
9
投票

我已经使用selenium解决了这个问题。

然后我下载了 PhantomJS 驱动程序以在没有浏览器窗口的情况下使用 selenium 并将其添加到 PATH 中。

最后,我使用以下Python脚本:

from selenium import webdriver
    
myscript = settings.get_js_code() # here I get content of *.js file
driver = webdriver.PhantomJS()
driver.get(url)
result = driver.execute_script(myscript)
driver.quit()

注意:您的脚本必须返回一些内容才能获得结果。


0
投票

我使用 selenium 库和 Google Chrome 驱动程序开发了一个功能(对于最新版本的 selenium,PhantomJS 驱动程序已过时)。

这是代码:

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


def execute_script_on_url(
        page_url,
        js_script,
        load_wait_time=1,
        script_wait_time=0
):
    service = Service(ChromeDriverManager().install())
    options = webdriver.ChromeOptions()

    # Stop browser windows to pop up.
    options.add_argument('--headless')

    driver = webdriver.Chrome(service=service, options=options)
    try:
        # Open the web page and wait for it to load.
        driver.get(page_url)
        time.sleep(load_wait_time)

        # Execute the JS script and wait for it to finish.
        result = driver.execute_script(js_script)
        time.sleep(script_wait_time)

        return result
    finally:
        driver.quit()

此函数将 page_url 和 js_script 作为文本执行。 您可以将文件转换为如下文本:

script = open('./the-file-route.js', 'r').read()

然后你可以像这样使用该函数: (例如)

result = execute_script_on_url('https://www.google.com/', '../my-script.js')

如果脚本返回某些内容,那么它将存储在

result
变量中。例如,如果您的 JavaScript 代码如下所示(愚蠢的示例):

return [1, 2, 3, 4];

然后如果你在 Python 中打印

result
:

print(result)
# Expected output: [1, 2, 3, 4]
© www.soinside.com 2019 - 2024. All rights reserved.