使用HtmlUnit实现自动化

时间:2017-07-14 08:12:30

标签: java htmlunit htmlunit-driver

我正在尝试打开网页并在java中使用HtmlUnit点击其链接,但是我收到了初始化错误。有人可以告诉我如何解决此错误。 这是我的代码:

package learn1;
import java.net.URL;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

import org.junit.Test;


public class SearchExample{

    public static void main(String args[]) throws Exception {
        SearchExample exe=new SearchExample();
        exe.testSearch();

    }

    @Test
    public void testSearch() throws Exception {

        final WebClient webClient = new WebClient();
        webClient.setThrowExceptionOnScriptError(false);
        final URL url = new URL("http://www.google.com");
        final HtmlPage page = (HtmlPage)webClient.getPage(url);
        System.out.println(page.getTitleText());
        HtmlForm form = (HtmlForm) page.getForms().get(0);
        HtmlTextInput text = (HtmlTextInput) form.getInputByName("q");
        text.setValueAttribute("HtmlUnit");
        HtmlSubmitInput btn = (HtmlSubmitInput) form.getInputByName("btnG");
        HtmlPage page2 = (HtmlPage) btn.click();
        HtmlAnchor link = page2.getAnchorByHref("http://htmlunit.sourceforge.net/");
        HtmlPage page3 = (HtmlPage) link.click();
        System.out.print(page3.getTitleText());
        /*assertEquals(page3.getTitleText(), "htmlunit - Welcome to HtmlUnit");
        assertNotNull(page3.getAnchorByHref("gettingStarted.html"));*/
     }
}

我收到以下错误:

  

线程中的异常" main" java.lang.NoClassDefFoundError:   组织/阿帕奇/ HTTP /客户/ CredentialsProvider       在learn1.SearchExample.testSearch(SearchExample.java:26)       在learn1.SearchExample.main(SearchExample.java:19)引起:java.lang.ClassNotFoundException:   org.apache.http.client.CredentialsProvider       at java.net.URLClassLoader.findClass(Unknown Source)       at java.lang.ClassLoader.loadClass(Unknown Source)       at sun.misc.Launcher $ AppClassLoader.loadClass(Unknown Source)       at java.lang.ClassLoader.loadClass(Unknown Source)       ......还有2个

我已经导入com.gargoylesoftware.htmlunit.WebClient

时无法理解我收到此错误的原因

1 个答案:

答案 0 :(得分:0)

您缺少其他依赖项,CredentialsProvider来自Apache Http Components。 这是完整的依赖列表: http://htmlunit.sourceforge.net/dependencies.html