Java SE: open a web page and click a button


I have a Java 7 program (using WebStart technology, only for computers with Windows 7/8).

I need to add a function so that my program clicks a button on a page with a known URL (https).

Some people offer WebKit SWT, but I went to their site and they say that the project was discontinued. ( http://www.genuitec.com/about/labs.html )

Other people say that JxBrowser is the only option, but it looks like it exceeds $ 1,300, which is crazy. ( http://www.teamdev.com/jxbrowser/onlinedemo/ )

I am looking for something simple, free, light and able to open an HTTPS link, parse HTML, access a button through the DOM and click on it. Maybe some JavaScript too, if there are JS handlers.

Thank you for your help.

+4
source share
2 answers

You may be looking for HtmlUnit , the "GUI-Less browser for Java programs."

Here's an example of the code that google.com opens, searches for "htmlunit" using the form, and prints the number of results.

 import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.*; public class HtmlUnitFormExample { public static void main(String[] args) throws Exception { WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage("http://www.google.com"); HtmlInput searchBox = page.getElementByName("q"); searchBox.setValueAttribute("htmlunit"); HtmlSubmitInput googleSearchSubmitButton = page.getElementByName("btnG"); // sometimes it "btnK" page=googleSearchSubmitButton.click(); HtmlDivision resultStatsDiv = page.getFirstByXPath("//div[@id='resultStats']"); System.out.println(resultStatsDiv.asText()); // About 309,000 results webClient.closeAllWindows(); } } 

Other options:

  • Selenium : opens a browser like Firefox and manages it.
  • Watij : a browser will also open, but in its own window.
  • Jsoup : Good parser. However, JavaScript does not work.
+8
source

Your question is hard to understand what you want. If you have a webstart application and want to open the link in a browser, you can use the java.awt.Desktop.getDesktop().browse(URI) method.

 public void openLinkInBrowser(ActionEvent event){ try { URI uri = new URI(WEB_ADDRESS); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException | IOException e) { //System.out.println("THROW::: make sure we handle browser error"); e.printStackTrace(); } } 
+1
source

Source: https://habr.com/ru/post/1482682/


All Articles