如何使用php通过apache服务器调用selenium来执行python脚本?

2024-10-02 08:26:20 发布

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

我想通过我在本地apache服务器上的站点用Python执行以下脚本:

#!/Python34/python
from selenium import webdriver 
driver=webdriver.Firefox()
driver.get("C:\wamp64\www\desenvol\index.html")
elem1 = driver.find_element_by_link_text("call another page")
elem1.click()

apache配置正确,这是我在php代码中使用的页面:

^{pr2}$

Tags: fromimport服务器脚本get站点apachewww
2条回答

我没有用简单的方法解决它。所以,我就是这么做的:

  • 首先,我创建了一个包含一个表和两列(id和'numero'的数据库)
  • 然后我在python中创建一个循环,从特定id(0)中的'numero'获取值,并比较这个值是否更改,如果发生这种情况,python将执行web驱动程序命令
  • 最后,我在html页面中创建一个php脚本,以更新特定id(0)中的值

所以,这是我的密码。。。在

python最终代码:

#!/Python34/python #from __future__ import print_function #NAO NECESSARIO Estava No exemplo do PyMySQL,aparentemente nao necessario import time #Importa a função do delay import pymysql #importa biblioteca para conexao com o python from selenium import webdriver #biblioteca que me permite acessar o navegador conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='samsung', db='tccdia')#string de conexao com o MySQL status = 1 #defina essa variavel para funcionar como uma chave que impede a execução do webdriver assim que o script iniciar ValorReferencia = 1 #valor para verificar se o valor do DB foi altera #chave = 0 #NAO NECESSARIO while 1<2: cur = conn.cursor() cur.execute("SELECT numero FROM cw_lampada WHERE id = 0") result = cur.fetchone()#criei uma variavel para armazenar esse valor porque ele apaga ValorAtual = result ValorAtual = ValorAtual[-1] # Tira aspas e virgulas Funcionou mas nao entendi o procedimento print ("valor atual: ",ValorAtual," tipo: " ,type(ValorAtual)) if status == 1: ValorReferencia = ValorAtual status = 0 #chave=1 #NAO NECESSARIO print ("valor referencia: ",ValorReferencia," tipo: " ,type(ValorReferencia)) #if chave ==1: ##NAO NECESSARIO Maybe this if ins't necessary if ValorAtual != ValorReferencia : driver=webdriver.Firefox() #Abre o navegador em determinado endereco e abre link driver.get("C:\wamp64\www\desenvol\index.html") elem1 = driver.find_element_by_link_text("call another page") elem1.click() driver.close() status = 1 #chave = 0 #NAO NECESSARIO cur.close() time.sleep(2) #tempo de espera #conn.close() #NAO NECESSARIO nao faria sentido ficar abrindo e fechando conexao se o tempo de reconexao eh curto

和13;
和13;

MySQL数据库类似于:

和13;

和13;

HTML是:

<!doctype html> <html lang="pt_BR"> <head> <meta charset="utf-8"> <title>lampada</title> </head> <body> <?php require 'config.php'; require 'connection.php'; #connection deve ser chamado anetes do database require 'database.php'; ?> <form action="" method="post"> <input type="submit" value="Clicar" name="botao" style="width: 900px; height: 200px;"> </form> <?php if(isset($_POST["botao"])){ echo "botão foi clicado"; $numero = $numero+1; $atualizar = array( 'numero' => $numero ); DBUpdate('lampada', $atualizar, 'id=0'); ?> </body> </html>

和13;
和13;

当然,有一个更简单和直接的方法来解决这个问题,但我就是这么做的。我希望我对其他有问题的人有用

提供python脚本的完整路径,即:

shell_exec('python /full/path/to/hello.py');

如果您想安全起见,还需要提供python二进制文件的完整路径。在

^{pr2}$

要找到python二进制文件的完整路径,请打开shell并键入:

which python

  1. 确保apache用户对hello.py具有执行权限。在
  2. 我在你的html上没有看到任何带有文本“call another page”的元素。在

更新:

也可以使用python的SimpleHTTPServer,类似于:

from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
class GetHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        self.send_response(200)
        self.end_headers()
        #self.wfile.write(message)
        if (parsed_path.query == "LightON"):
            from selenium import webdriver 
            driver=webdriver.Firefox()
            driver.get("http://stackoverflow.com")
            elem1 = driver.find_element_by_link_text("Questions")
            elem1.click()
            self.wfile.write("Command Executed")
        return

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 8080), GetHandler)
    print 'Starting server, use <Ctrl-C> to stop'
    server.serve_forever()

上面的代码将在端口8080上打开一个webserver,并等待一个LightON请求,在接收到它之后,执行selenium代码。在

要激活它,只需创建一个指向它的链接,比如

<a href="http://localhost:8080/LightON"> LightON </a>

PS:我已经测试了代码,它按预期工作。在

相关问题 更多 >

    热门问题