Java SE: Open Web Page and Click a Button

前端 未结 2 1838
北恋
北恋 2021-02-04 12:41


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

I need to add a function so that my program clicks a button on a page with know

相关标签:
2条回答
  • 2021-02-04 13:14

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

    Here's a sample code that opens google.com, 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's "btnK"
            page=googleSearchSubmitButton.click();
    
            HtmlDivision resultStatsDiv =
                                    page.getFirstByXPath("//div[@id='resultStats']");
    
            System.out.println(resultStatsDiv.asText()); // About 309,000 results
            webClient.closeAllWindows();
        }
    }
    

    Other options are:

    • Selenium: Will open a browser like Firefox and operate it.
    • Watij: Also will open a browser, but in its own window.
    • Jsoup: Good parser. No JavaScript, though.
    0 讨论(0)
  • 2021-02-04 13:37

    Your question is kind of difficult to understand what you want. If you have a webstart app and want to open a link in the 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();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题