Programmatically click a webpage button
How to programmatically click a webpage button in Java?
For this button:
<div id="titlebutton" >Button</div> In Javascript, it will work as follows:
var newWin = window.open(siteYouHaveAccessTo); newWin.document.getElementById('titlebutton').click(); I was wondering how I will do it in Java and not in Javascript (is there any way to do this using Java alone or do I need to import / use Javascript?).
Edit:
Pressing a button will call a function called setText (). I'm not sure how to send a similar request like this function? Would it help me if I inserted the function code?
You cannot "programmatically" click a button using Java only, so we use JavaScript. If you want to gain control over the browser, for example, by pressing buttons and filling in text fields, you will have to use an automation tool. An automation tool using Java is Selenium. This is commonly used to automate testing, but will do what you want.
I'm not sure if this is what you are looking for, but if what you want to do is just make an 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 corresponding to the URL of your site. You can send any data that you want to send by clicking the button as request parameters in the URL in the form of key / value pairs.
If you are looking for browser automation, you can use selenium or java.awt.Robot
The robot can send "clicks" to the OS. used it together with vbs scripts to first make sure that a particular window has focus, and then send text and clicks and finally save the results ... not very well, as if the page changed things, then you need to make adjustments . But the man I made used it for 4 years.