从webpag在服务器上启动python脚本

2024-04-27 09:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在服务器上从网页启动python脚本?你知道吗

在工作中,我使用selenium编写了一个简单的python脚本来完成一项例行工作(打开一个网页并单击几个按钮)。你知道吗

我希望能够远程启动(仍在公司网络上),但由于工作中的安全性/权限,我不能使用telnet/shh/etc或安装PHP(我读过这是一种方法)。你知道吗

我以前做过简单的python服务器,它可以发送/接收REST请求,但是我找不到使用javascript(我对javascript有点熟悉)从网页发送的方法。 我发现了一些搜索结果,其中有人建议使用AJAX,但我无法让它正常工作

它只需要一个空白页面,上面有一个按钮,它就可以向我的服务器发送一个请求,然后服务器就会启动脚本。你知道吗

谢谢你的帮助。你知道吗


Tags: 方法网络服务器脚本权限网页远程selenium
3条回答

我的例子是使用Flask

因为你不需要一个空白,打开URL,你的selenium就可以运行了。你知道吗

from flask import Flask
app = Flask(__name__)

@app.route("/start")
def yourfunction():
    #start whatever you like here
    return #whatever you like to display eg. status / result 

引用:Flask

有多种方法可以让你开始。 您可以尝试通过CGI提供Python脚本。你知道吗

或者,您可以将脚本包装到web框架中,例如FlaskDjango。 考虑到您的代码相对较小,不需要在SQL中存储数据,也不需要与用户交互,您应该使用Flask,因为它非常轻量级,并且在web上有很好的文档记录。你知道吗

一般来说,您需要编写一个简单的服务器,在GET请求时返回HTML表单,在POST请求时处理该表单。你知道吗

例如,使用Bottle的一个非常简单但完全有效的示例:

from bottle import get, post, run

from subprocess import check_output

@get('/')
def home():
    return '<form method="post"><input type="submit" value="Click me!"></form>'

@post('/')
def on_submit():
    return "Today's date is " + check_output(['date']).decode()

run(host='localhost', port=8080)

或者只使用标准的图书馆资料http.server,这是相同的概念,不过还有更多的样板:

import http.server
import socketserver

from subprocess import check_output

class Handler(http.server.BaseHTTPRequestHandler):
    def html_preamble(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        self.html_preamble()
        response = '<form method="post"><input type="submit" value="Click me!"></form>'
        self.wfile.write(response.encode('utf-8'))

    def do_POST(self):
        self.html_preamble()
        response = "Today's date is " + check_output(['date']).decode()
        self.wfile.write(response.encode('utf-8'))

PORT = 8081
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

无论如何,既然您是用Python编写Selenium脚本的,那么您可能只需要导入相关函数并直接调用它们,而不是通过子进程,只需小心资源泄漏,并确保您的函数清除了不需要在请求之间保留的任何资源。你知道吗

相关问题 更多 >