简体   繁体   English

在 Python 的 Selenium chromedriver 中执行无限 javascript 循环时陷入困境

[英]Getting stuck executing infinite javascript loop in Python's Selenium chromedriver

I am trying to build a service where users can insert their Javascript code and it gets executed on a website of their choice.我正在尝试构建一个服务,用户可以在其中插入他们的 Javascript 代码并在他们选择的网站上执行。 I use webdriver from python's selenium lib and chromedriver.我使用 python 的 selenium lib 和 chromedriver 中的 webdriver。 The problem is that the python script gets stuck if user submits Javascript code with infinite loop.问题是,如果用户无限循环提交 Javascript 代码,python 脚本就会卡住。

The python script needs to process many tasks like: go to a website and execute some Javascript code. python 脚本需要处理许多任务,例如:访问网站并执行一些 Javascript 代码。 So, I can't afford to let it get stuck.所以,我不能让它卡住。 Infinite loop in Javascript is known to cause a browser to freeze.众所周知,Javascript 中的无限循环会导致浏览器冻结。 But isn't there some way to set a timeout for webdriver's execute_script method?但是有没有办法为 webdriver 的 execute_script 方法设置超时? I would like to get back to python after a timeout and continue to run code after the execute_script command.我想在超时后回到 python 并在 execute_script 命令后继续运行代码。 Is this possible?这可能吗?

from selenium import webdriver
chromedriver = "C:\chromedriver\chromedriver.exe"
driver = webdriver.Chrome(chromedriver)
driver.get("http://www.bulletproofpasswords.org/") # Or any other website
driver.execute_script("while (1); // Javascript infinite loop causing freeze")

You could set a timeout for your driver.execute_script("while (1);") call.您可以为driver.execute_script("while (1);")调用设置超时。 I have found another post that could solve this issue.我找到了另一个可以解决这个问题的帖子

Basically, if you are on a Unix system, you could use signal to set a timeout for your driver.execute_script("while (1); call.基本上,如果您在 Unix 系统上,您可以使用信号为您的driver.execute_script("while (1); call.

Or if you could run it in a separate process and then end the process if it takes too long using multiprocessing.Process .或者,如果您可以在单独的进程中运行它,然后在使用multiprocessing.Process花费太长时间时结束该进程。 I'm including the example that was given in the other post:我包括在另一篇文章中给出的例子:

import multiprocessing
import time

# bar
def bar():
    for i in range(100):
        print "Tick"
        time.sleep(1)

if __name__ == '__main__':
    # Start bar as a process
    p = multiprocessing.Process(target=bar)
    p.start()

    # Wait for 10 seconds or until process finishes
    p.join(10)

    # If thread is still active
    if p.is_alive():
        print "running... let's kill it..."

        # Terminate
        p.terminate()
        p.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM