【问题标题】:How to execute a python script with selenium called by php through apache server?如何通过 apache 服务器使用 php 调用的 selenium 执行 python 脚本?
【发布时间】:2016-09-27 16:16:49
【问题描述】:

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

【问题讨论】:

  • 当前代码有什么错误?您的 Apache 用户是否设置了无密码 sudo?
  • 实际上只是第一个按钮很重要(灯亮),因为我使用的是 WAMP。问题是没有任何反应,出现加载符号,但 Firefox 浏览器没有按预期打开。
  • 您正在使用 WAMP?那么你甚至有sudo 命令吗?你用的是什么外壳?
  • 我更新了代码。我正在使用 Windows 10 中的 CMD-DOS。
  • python%PATH% 上吗?在常规命令提示符下运行命令会发生什么?

标签: php python html apache selenium


【解决方案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. 我在您的 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:我已经测试了代码,它按预期工作。

【讨论】:

  • 没用。因为我的问题太复杂了。首先,使用 python 是解决我使用 ENC28J60 以太网 LAN 网络模块的 Arduino Web 服务器问题的一种方法。 python脚本将输入arduino IP(其中是:C:\ wamp64 \ www \ desenvol \ index.html,将是Arduino本地IP)并点击一些链接......我的问题是语法原因我已经尝试使用 print (" ") 用 python 做一个页面,效果很好。
  • 我认为你必须停下来好好想想你需要什么,有时离开电脑一会儿会有帮助。总帐。
  • 我的老师说我可以使用Json和jquery来解决我使用python脚本的问题,但是这个问题很有趣,我想找到答案。
  • 你为什么不使用 python SimpleHTTPServer ? docs.python.org/2/library/simplehttpserver.html
  • 出于好玩,我已经发布了python网络服务器代码演示;)
【解决方案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

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>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 2017-03-22
    • 2017-02-05
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多