![](/img/trans.png)
[英]How to execute shell script which contains python execution from php apache server?
[英]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>
</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
hello.py
具有執行權限。更新:
您還可以使用 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:我已經測試了代碼,它按預期工作。
我沒有以簡單的方式解決它。 所以,這就是我所做的:
所以,這是我的代碼......
#!/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
create database tccdia; use tccdia; create table cw_lampada( id int primary key, numero int );
<!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.