簡體   English   中英

如何使用 php 通過 apache 服務器調用 selenium 執行 python 腳本?

[英]How to execute a python script with selenium called by php through apache server?

我想通過我在本地 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 代碼一起使用的頁面:

<!doctype html>
<html>
<head>
<title>Light Controller</title>
</head>


<?php
if (isset($_POST['LightON']))
{
exec('python hello.py');
echo("on");
}
?>

<form method="post">
<button name="LightON">Light ON</button>&nbsp;
</form> 


</html>

提供 python 腳本的完整路徑,即:

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

如果您想安全起見,還請提供 python 二進制文件的完整路徑。

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

要查找 python 二進制文件的完整路徑,請打開 shell 並鍵入:

which python

  1. 確保 apache 用戶對hello.py具有執行權限。
  2. 我在您的 html 上沒有看到任何帶有文本“調用另一個頁面”的元素。

更新:

您還可以使用 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:我已經測試了代碼,它按預期工作。

我沒有以簡單的方式解決它。 所以,這就是我所做的:

  • 首先,我創建了一個包含一個表和兩列(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

MySQL 數據庫類似於:

 create database tccdia; use tccdia; create table cw_lampada( id int primary key, numero int );

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>

當然,有一種更簡單直接的方法可以解決這個問題,但這就是我所做的。 我希望我對其他有同樣問題的人有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM