run selenium-python script, from a web browser

I am using selenium and python to restart a device, I already managed to make it work and I restarted the device, now I am trying from a web page with a button or link, to execute the python code remotely, but I can't that the script runs, could you give me an idea or procedure to make the code run by clicking on a button or link.
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time
import random
import os
def login():
browser = webdriver.Firefox()
browser.get('http://192.168.2.2/')
sleep_random = random.randint(3, 7)
time.sleep(sleep_random)
username_input = browser.find_element_by_xpath(
"/html/body/td[2]/input")
password_input = browser.find_element_by_xpath(
"/html/body/td[2]/input")
username_input.send_keys("Admin")
password_input.send_keys("12345")
login_button = browser.find_element_by_id('login')
login_button.click()
time.sleep(5)
browser.get('http://192.168.2.2/reboot')
time.sleep(5)
browserclose = "firefox"
os.system("pkill "+browserclose)
login()
Answer
Solution:
You are trying to:
- Visit a webpage on computer A
- Click a button on the webpage
- Have computer A run this script which reboots computer B
If so, you need to put the script behind a server like django or flask running on computer A. You'll need some authentication and stuff like Apache to host it securely.
Here is a bit of what you'll need on computer A to host the button. Note that the functionreboot
calls your functionlogin()
:
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/reboot', methods=['POST'])
def reboot():
print('reboot called')
login()
return "Reboot command issued"
@app.route('/', methods=['GET', 'POST'])
def home():
# better to serve a template here, but...
return """
<form action="/reboot" method="post">
<input type="submit" name="reboot" value="Reboot" />
</form>
"""
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5010)
Oh, and why aren't you usingbrowser.quit()
instead of that pkill hack?
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.