Search code examples
pythonrequestbotsmechanize

Python issues, mechanize bots


I'm trying to make a bot in order to reset my router easily, so I'm using mechanize for this task.

import mechanize

br = mechanize.Browser()
br.set_handle_robots(False)
response = br.open("http://192.168.0.1/")

br.select_form(nr=0)
br.form['loginUsername']='support'
br.form['loginPassword']='71689637'
response=br.submit()

if(response.read().find("wifi")) != -1:
    # ????? 

If it finds the string 'wifi', it means the bot has logged in, but here's where I get stuck, because the restart button is in another tab (Another page, I guess that from the same object indicating the new URL it should be able to follow the redirection URL without logging off). However, the button from that tab is, well, a button but not a form.

Picture 1:

pic 1

Picture 2:

pic 2

And here's the source:

https://github.com/SharkiPy/Code-stackoverflow/blob/master/Source


Solution

  • Here is a start of code using Selenium, with hidden browser. You just have to add the actions you take when browsing through your router. I hope it can get you started!

    import time
    from selenium import webdriver
    from selenium.common.exceptions import WebDriverException, NoSuchElementException,InvalidElementStateException,ElementNotInteractableException, StaleElementReferenceException, ElementNotVisibleException
    from selenium.webdriver.common.keys import Keys
    # There may be some unnecessary import above
    
    from selenium.webdriver.chrome.options import Options
    
    options_chrome = webdriver.ChromeOptions()
    options_chrome.binary_location = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' # PATH to your chrome driver (you can also use firefox or any other browser, but options below will not be exactly the same
    prefs = {"profile.default_content_setting_values.notifications" : 2} # disable notification by default
    options_chrome.add_experimental_option("prefs",prefs)
    
    #### below are options for headless chrome
    #options_chrome.add_argument('headless')
    #options_chrome.add_argument("disable-gpu")
    #options_chrome.add_argument("--start-maximized")
    #options_chrome.add_argument("--no-sandbox")
    #options_chrome.add_argument("--disable-setuid-sandbox")
    #### You should uncomment these lines when your code will be working
    
    # starting browser : 
    browser = webdriver.Chrome( options=options_chrome)
    
    # go to the router page :
    browser.get("http://192.168.0.1/")
    
    # connect 
    elem = browser.find_element_by_id("loginUsername")
    elem.send_keys('support')
    elem = browser.find_element_by_id("loginPassword")
    elem.send_keys('71689637')
    elem.send_keys(Keys.RETURN)
    
    # here you need to find your button and click it
    button = browser.find_element_by_[Whatever works for you]
    button.click()