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

时间:2016-05-29 22:04:38

标签: php python html apache selenium

我想通过本地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>

2 个答案:

答案 0 :(得分:1)

提供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. 我没有看到任何带有文字的元素&#34; 调用另一个页面&#34;在你的HTML上。
  3. <强>更新

    你也可以使用python&#39; s 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代码。< / p>

    激活它只是创建一个链接,如

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

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

答案 1 :(得分:0)

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

  • 首先,我创建了一个包含一个表和两列(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>

当然,有一种更简单直接的解决方法,但这就是我所做的。我希望我对其他问题有所帮助。

相关问题