2011-02-02 12 views
9

Sto provando a utilizzare HtmlUnit in Java per accedere a un sito Web. Innanzitutto inserisco il nome utente e la password. Dopo di che ho bisogno di selezionare un'opzione da una casella a discesa. l'inserimento dell'utente e della password sembrava aver funzionato, ma quando provo a selezionare l'elemento dalla casella a discesa ottengo degli errori. Qualcuno può aiutarmi a risolvere questo? Il mio codice è il seguente:Come utilizzare HtmlUnit in Java?

import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlElement; 
import com.gargoylesoftware.htmlunit.html.HtmlOption; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlSelect; 


public class homePage { 
    public static void main(String[] args) throws Exception { 

    final WebClient webClient = new WebClient(); 
    final HtmlPage page = webClient.getPage("website name here"); 
    HtmlElement usrname = page.getElementByName("username"); 
    usrname.click(); 
    usrname.type("myusername"); 
    HtmlElement psswrd = page.getElementByName("password"); 
    psswrd.click(); 
    psswrd.type("mypassword"); 
    HtmlSelect select = (HtmlSelect) page.getElementById("cmbProducts"); 
    HtmlOption option = select.getOptionByValue("ITDirect"); 
    select.setSelectedAttribute(option, true); 
    HtmlElement signin = page.getElementByName("SignIn"); 
    signin.click(); 
    System.out.println(page.getTitleText()); 
    webClient.closeAllWindows(); 
    } 
} 
+4

ci dice esattamente ciò che gli errori che si ottiene sarebbe molto utile. – MatrixFrog

risposta

3

Ecco il codice dai test di unità per HTMLunit.

final HtmlSelect select = form.getSelectsByName("select1").get(0); 
final List<HtmlOption> expected = new ArrayList<HtmlOption>(); 
expected.add(select.getOptionByValue("option1")); 
expected.add(select.getOptionByValue("option3")); 

Si noti che utilizzano getSelectsByName not getElementById.

Ecco un collegamento a questi test di unità in modo da poter vedere come prescrivono utilizzando l'API. http://htmlunit.sourceforge.net/xref-test/com/gargoylesoftware/htmlunit/html/HtmlSelectTest.html

3

Ottieni il nome utente e la password di accesso.

Ecco un esempio:

HtmlPage page3; 
    page3 = webClient.getPage("Website"); 
    HtmlForm loginForm = page3.getFormByName("loginForm"); 
    HtmlTextInput username = loginForm.getInputByName("NameofUsernameElement"); 
    HtmlPasswordInput pass = loginForm.getInputByName("NameofPassowordElement"); 
    HtmlSubmitInput b = loginForm.getInputByValue("LoginButtonValue"); 

    username.setValueAttribute("Actualy Username"); 
    pass.setValueAttribute("Actual Password"); 
    HtmlPage page2; 
    page2 = b.click();