Run Python command with Selenium called by PHP through Apache

Asked

Viewed 675 times

6

I want to run the following script in Python by a web site on the server:

#!/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 is well configured and I used the page with the web site contains the following in php:

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

    <?php
        if (isset($_POST['LightON']))
        {
            echo exec('python hello.py');
            echo("on");
        }
        if (isset($_POST['LightOFF']))
        {
            shell_exec("sudo python /var/www/lightsoff.py");
            echo("Off");
        }
    ?>

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

What should I do?

  • Heitor, I didn’t understand a thing, the excerpt driver.find_element_by_link_text looks for a link whose text is "call Another page" but this text does not exist in html. Tell me something, what you want is to fire the button using the python code?

  • What’s the problem? What should I do is very subjective. Looking only at the code I imagine the script hello.py is not running (probably because it is not in the same directory).

2 answers

0

A few thoughts before we move on:

  • If the script is in Python why the whole page is not already in Python?
  • If the page is in PHP then the script is not in PHP?

However, with years of experience we learn how to deal with the customer’s environment and not always the same comes from a perfect architecture or that makes sense, so let’s move on with your scenario.

In PHP has a shell_exec function. Which means most of your path is on the move.

Example of execution:

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

In your Python script put the following at the beginning:

#!/usr/bin/env python

After this adjustment in the script make it executable on linux platforms:

chmod +x myscript.py

Ready.

-4

I didn’t solve my problem in an easy way, so what I did was:

  • I first created a database with a table with two columns(id and number).

  • So I looped in python to take the value of 'number' in a specific id (0) and compare if that value has changed, if that happens pytho will run the web driver command.

  • Finally, I made a php script, inside an html page, to update this value in that specific id (0).

This is my code...

The python final code:

#!/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

The Mysql database was Something like:

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

And the HTML was:

<!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>

Surely there are easier and more direct ways to solve this but that’s what I did. I hope this solution helps others with the same problem.

  • 4

    Could translate the answer to English?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.