1478963
1478963

Reputation: 1216

Programmatically click a webpage button

How to programmatically click a webpage button in Java?

Given this button:

 <div id="titlebutton" >Button</div>

In Javascript it would work like this:

var newWin = window.open(siteYouHaveAccessTo);
newWin.document.getElementById('titlebutton').click();

I was wondering how I would do this in Java, not Javascript (Is there a way of doing it with Java alone or do I have to import/use Javascript?).

Edit:

Clicking the Button will result in a call of a function called setText(). I am not sure how I would send a similar request as this function? Would it help if I pasted the function code?

Upvotes: 5

Views: 30485

Answers (3)

tgkprog
tgkprog

Reputation: 4598

if you looking for browser automation can use selenium or java.awt.Robot

Robot can send 'clicks' to the OS. have used it along with vbs scripts to first make sure a particular window has focus and then send text and clicks, and finally save results ... not very good as if the page changes things then you need to make adjustments. But the person I made this used it for 4 years.

Upvotes: 0

BaconCookies
BaconCookies

Reputation: 84

You can't 'programmatically' click a button with Java alone, which is why we use JavaScript. If you want to get into controlling the browser such as clicking buttons and filling text fields you would have to use an automation tool. An automation tool that uses Java is Selenium. This is typically used as for test automation, but will do what you want it to do.

See http://docs.seleniumhq.org/

Upvotes: 7

Jeshurun
Jeshurun

Reputation: 23186

I'm not sure if this is what you are looking for, but if what you are looking to do is simply make a HTTP request in Java, this should do the trick:

HttpURLConnection urlConnection = null;
URL urlToRequest = new URL("http://yoursite.com/yourpage?key=val&key1=val1");
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONN_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);

// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
    // handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
    // handle any other errors, like 404, 500,..
}

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

// Process response

Replace the timeout constants with your own values, and the URL to match that of your website. You can send any data you want to send with the click of the button as query parameters in the URL in the form of key/value pairs.

Upvotes: 0

Related Questions