Question

I would like to be able to log into a website or server by having the user input the username and password. The python program would then log into a website and print the source code of the redirected URL. I am able to print the source code of a webpage with the following code from eHow. The server I am trying to access is 192.168.0.1 which is the wifi server of my home network.

import urllib.request
from array import array
file = open("DLINK.txt","w")
filehandle = urllib.request.urlopen('http://192.168.0.1')
for lines in filehandle.readlines():
    print(lines)
    file.write(str(lines))
file.close()
filehandle.close()
Was it helpful?

Solution

I'm guessing the D-Link is using Basic Authentication. In that case you may use this code from the documentation in order to get the through the login.

    import urllib.request
    # Create an OpenerDirector with support for Basic HTTP Authentication...
    auth_handler = urllib.request.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='D-Link', uri=url, user=username, passwd=password)
    opener = urllib.request.build_opener(auth_handler)
    urllib.request.install_opener(opener)
    f = urllib.request.urlopen(url)
    print(f.status)
    print(f.reason)
    print(f.read().decode('utf-8'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top