Goal: Automating Open browser and the process of filling in login credentials on a login form using site login credentials.
1st I wrote the python3 script login_script.py
and when I hit from the terminal
$ python3 login_script.py
it’s working correctly without any issues but then I hit the same script from my Laravel it’s not working.
My Python Code is:
login_script.py
import subprocess
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# Install Selenium if not already installed
try:
import selenium
except ImportError:
print("Installing Selenium...")
subprocess.run(['pip', 'install', 'selenium'])
# Define your credentials and login URL
username = 'myusername'
password = 'mypassword'
login_url = 'https://example.com/login'
# Create a WebDriver instance (assuming Chrome)
driver = webdriver.Chrome()
# Maximize the browser window
driver.maximize_window()
# Navigate to the login page
driver.get(login_url)
# Wait for the page to load (you might need to adjust the time depending on the page load time)
#time.sleep(1)
# Find the username and password input fields and fill them in
username_field = driver.find_element(By.NAME, "username")
password_field = driver.find_element(By.NAME, "password")
username_field.send_keys(username)
password_field.send_keys(password)
# Submit the form
password_field.send_keys(Keys.RETURN)
# Optionally, you might want to add some delay here to allow time for the page to load
# Wait for the login process to complete
time.sleep(999999999) # Adjust as needed
# Close the browser session
#driver.quit()
My Laravel Code is:
PythonController.php
<?php
namespace ModulesSideMenuBuilderHttpControllers;
use IlluminateHttpRequest;
use IlluminateRoutingController;
use SymfonyComponentProcessExceptionProcessFailedException;
use SymfonyComponentProcessProcess;
use IlluminateSupportFacadesArtisan;
class PythonController extends Controller
{
public function openBrowser(Request $request)
{
try {
// Case 1:
$basePath = base_path();
$process = new Process(['python3', base_path() . '/open_browser.py']);
$process->run();
return $process->getOutput();
// Case 2:
// Activate virtual environment
$activate_command = 'source pythonenv/bin/activate';
// Run Python script within the activated virtual environment';
$python_command = 'python3 open_browser.py';
// Combine commands with && to execute sequentially
$command = "$activate_command && $python_command 2>&1";
// Execute the command and capture output
$output = shell_exec($command);
// Output the result
return response()->json(['output' => $output]);
} catch (Exception $e) {
return response()->json(['output' => $e->getMessage()]);
}
//exit();
}
}
Can you guide me as to why the browser does not open when I hit the .py file from Laravel and shows a blank page without any error?