Login programmatically
#1
Hey there, I am attempting to write a program in java that requires me to login to a website, instagram in this case. Having looked at various code snippets on the subject I am no closer to knowing how exactly this is done.
I am able to connect to the login page fine using this code:

Code:
public void connectTo(){
try{
URLObj = new URL("https://www.instagram.com/accounts/login/");
connect = URLObj.openConnection();
connect.setDoOutput(true);
System.out.print("Connected to "+ URLObj);
}
catch(MalformedURLException ex) {
System.out.println("the url isnt able to be parsed or wrong protocol");
System.exit(1);
}
catch(Exception exc){
System.out.println("exception "+ exc.getMessage());
System.exit(1);

}
}

My issue lies with writing too the username - password fields, I've snooped around in the inspect element and logged in a couple of times while looking at the network tab but I am unsure of what it is that I am actually trying to achieve. Some help would be appreciated, this is the code I attempted I feel it only works on outdated systems:
Code:
public void loginOtoScreen(String username, String pword){
try{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("username="+username+"&pass="+pword+"&submit=Login");
writer.close();

//buffered reader to now read urls input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));

String lineRead = "";

//read all lines of data and print to screen
while((lineRead = reader.readLine()) != null)
System.out.println(lineRead);
reader.close();
}
catch(Exception ex){
System.out.println("\n error reading or writing to url"+ex.getMessage());
}
}
Reply
#2
I'm not all that familiar with Java but I'm pretty sure you can do this with Pythons mechanize library or urllib together with a cookiejar. If the site requires JS you could use browser virtualization like Selenium. I think our Python expert Vector has done this before :p

... But now that I think about it, I think Selenium has Java compatibility as well: http://seleniumhq.github.io/selenium/doc...index.html

Sorry if this post isn't too much help, just some hints at some libraries that can be used.
Reply
#3
(03-11-2017, 10:32 PM)Insider Wrote: I'm not all that familiar with Java but I'm pretty sure you can do this with Pythons mechanize library or urllib together with a cookiejar. If the site requires JS you could use browser virtualization like Selenium. I think our Python expert Vector has done this before :p

... But now that I think about it, I think Selenium has Java compatibility as well: http://seleniumhq.github.io/selenium/doc...index.html

Sorry if this post isn't too much help, just some hints at some libraries that can be used.

I wouldn't call myself a Python expert, but yeah you can do this with Python. Mechanize is out of the question because instagram is Javascript heavy and Mechanize deals with HTTP. So it can't detect the form. It would be possible with Selenium. But you could probably also do it with the BeautifulSoup and Requests modules.

Code:
#!/bin/usr/env Python2.7

import requests
from bs4 import BeautifulSoup as bs

session = requests.session()

def log_in():
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    
    }
    
    data = {
            'username': 'Username',
            'password': 'Password',
            'grant_type': 'password',
            'login_submit': 'Log in'
                
    }
    
    login = session.post("http://instagram.com/accounts/login", data=data, headers=headers)
   
    print login.status_code


log_in()

Now this code is going spit 403 forbidden out since i have not provided a valid username nor password. But if you change it to valid ones i think it should work. To be honest i can't be bothered with setting up an instagram account. But i have tested this code, i know it connects and i know it recieves a 403 forbidden status code in return which would indicate an invalid password/username combination.

If you're going the selenium route the syntax is going to look a little like this. Remember this is Python,

Code:
#!/usr/bin/env Python2.7

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

username = "username"
password = "password"


driver = webdriver.Firefox()
driver.get("https://www.instagram.com/accounts/login/")

assert "Instagram" in driver.title
elem = driver.find_element_by_name("username")
elem.clear()
elem.send_keys(username)

elem = driver.find_element_by_name("password")
elem.clear()
elem.send_keys(password)

elem.send_keys(Keys.RETURN)

The webdriver should now be logged in if you assigned your username and password vars with the proper values. I have inspected the elements on Instagram and `find_element_by_name("username")` and `find_element_by_name("password")` will locate the login form correctly.


I'm sorry i can't help you as far as Java goes. But since Insider mentioned it could be done in Python i felt it may be beneficial to see how it's done with Python. Especially if you have any previous experience with Python i would recommend using that.
Reply
#4
Thanks for the reply guys, I had been giving selenium a try and think I have the code nailed down by reproducing vectors code in java. The only issue is I need geckodriver in my eclipse for selenium to work through firefox but every implementation i've seen uses a path to the geckodriver executable on windows and no examples of how it's done on linux :/

But thanks guys I'll keep at it, probably figure it out eventually.
Reply
#5
(03-12-2017, 08:10 PM)wraith Wrote: Thanks for the reply guys, I had been giving selenium a try and think I have the code nailed down by reproducing vectors code in java. The only issue is I need geckodriver in my eclipse for selenium to work through firefox but every implementation i've seen uses a path to the geckodriver executable on windows and no examples of how it's done on linux :/

But thanks guys I'll keep at it, probably figure it out eventually.

Ah! Never fear for Vector is here. Open up your terminal, and please type this command.

Code:
echo $PATH

It's going to show you something like:

Code:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:

So after you download Geckodriver, make sure you make the binary executable by setting it's permissions with `chmod +x geckodriver`. Then just drop the binary in `/usr/bin` for example. As long as it is a location in your $PATH you should be good.
Reply
#6
(03-12-2017, 09:56 PM)Vector Wrote:
(03-12-2017, 08:10 PM)wraith Wrote: Thanks for the reply guys, I had been giving selenium a try and think I have the code nailed down by reproducing vectors code in java. The only issue is I need geckodriver in my eclipse for selenium to work through firefox but every implementation i've seen uses a path to the geckodriver executable on windows and no examples of how it's done on linux :/

But thanks guys I'll keep at it, probably figure it out eventually.

Ah! Never fear for Vector is here. Open up your terminal, and please type this command.

Code:
echo $PATH

It's going to show you something like:

Code:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:

So after you download Geckodriver, make sure you make the binary executable by setting it's permissions with `chmod +x geckodriver`. Then just drop the binary in `/usr/bin` for example. As long as it is a location in your $PATH you should be good.

I had gave permission and exported to my path, but i'll give this a try! Cheers.
Reply
#7
(03-13-2017, 12:08 AM)wraith Wrote:
(03-12-2017, 09:56 PM)Vector Wrote:
(03-12-2017, 08:10 PM)wraith Wrote: Thanks for the reply guys, I had been giving selenium a try and think I have the code nailed down by reproducing vectors code in java. The only issue is I need geckodriver in my eclipse for selenium to work through firefox but every implementation i've seen uses a path to the geckodriver executable on windows and no examples of how it's done on linux :/

But thanks guys I'll keep at it, probably figure it out eventually.

Ah! Never fear for Vector is here. Open up your terminal, and please type this command.

Code:
echo $PATH

It's going to show you something like:

Code:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:

So after you download Geckodriver, make sure you make the binary executable by setting it's permissions with `chmod +x geckodriver`. Then just drop the binary in `/usr/bin` for example. As long as it is a location in your $PATH you should be good.

I had gave permission and exported to my path, but i'll give this a try! Cheers.

Yeah the trick is, you can't export a file to PATH only a directory. But if you drop the binary into a directory that's already in PATH then it should work just fine without having to export anything.
Reply
#8
I wrote one before with python and tried to just do it without opening a browser but it builds the html with js so back then I wasn't sure what to do so I let it open a browser window with selenium and went on with that.

Edit: Hey i went up and found an old little program I wrote, this has nothing to do with the login but maybe it helps with understanding selenium: https://pastebin.com/CrQjFu9Z

Hope it helps, and excuse my code it was from when I just started Big Grin it just downloads the pictures from an account, was a small project without API.
Reply