我用Java开发用于大学项目的http客户端登录到站点,从HTML数据中获取数据,完成并发送表单.我不知道使用哪个http lib:Apache HTTP客户端 - 不要创建DOM模型,而是使用http重定向,多线程.HTTPUnit - 创建DOM模型,并且易于使用表单,字段,表等,但我不知道如何使用多线程和代理设置.
有什么建议?
听起来你正在尝试创建一个网络抓取应用程序.为此,我推荐使用HtmlUnit库.
它使得使用嵌入在网页中的表单,代理和数据变得容易.我认为它使用Apache的HttpClient来处理HTTP请求,但这可能太低了,你不必担心.
使用此库,您可以像在Web浏览器中控制Web一样控制Web页面:单击按钮,键入文本,选择值.
以下是HtmlUnit入门页面的一些示例:
提交表格:
@Test
public void submittingForm() throws Exception {
final WebClient webClient = new WebClient();
// Get the first page
final HtmlPage page1 = webClient.getPage("http://some_url");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
final HtmlForm form = page1.getFormByName("myform");
final HtmlSubmitInput button = form.getInputByName("submitbutton");
final HtmlTextInput textField = form.getInputByName("userid");
// Change the value of the text field
textField.setValueAttribute("root");
// Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
webClient.closeAllWindows();
}
Run Code Online (Sandbox Code Playgroud)
使用代理服务器:
@Test
public void homePage_proxy() throws Exception {
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_2, "http://myproxyserver", myProxyPort);
//set proxy username and password
final DefaultCredentialsProvider credentialsProvider = (DefaultCredentialsProvider) webClient.getCredentialsProvider();
credentialsProvider.addProxyCredentials("username", "password");
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
webClient.closeAllWindows();
}
Run Code Online (Sandbox Code Playgroud)
该WebClient班是单线程的,所以每一个线程与网页交易将需要自己的WebClient实例.
除非您需要处理Javascript或CSS,否则您还可以在创建客户端时禁用它们:
WebClient client = new WebClient();
client.setJavaScriptEnabled(false);
client.setCssEnabled(false);
Run Code Online (Sandbox Code Playgroud)
HTTPUnit用于测试目的,我认为它不适合嵌入到您的应用程序中.
当您想要使用HTTP资源(如网页)时,我建议使用Apache HTTPClient.但是你可能会发现这个框架对于你的网页抓取用例来说是低级别的.所以为了这个目的,我建议像Apache Camel这样的集成框架.例如,以下路由读取网页(使用Apache HTTPClient),将HTML转换为格式良好的HTML(使用TagSoup)并将结果转换为XML表示以供进一步处理.
from("http://mycollege.edu/somepage.html).unmarshall().tidyMarkup().to("xslt:mystylesheet.xsl")
Run Code Online (Sandbox Code Playgroud)
您可以使用XPath进一步处理生成的XML,或者使用JAXB将其转换为POJO.
| 归档时间: |
|
| 查看次数: |
7749 次 |
| 最近记录: |