0
我是Java新手,需要编写各种Java应用程序来进行网页抓取和网页交互。Java和HTMLUnit:如何点击提交按钮?
我开始使用Selenium,但因为它直接与浏览器交互,所以对我的使用并不实际。
我需要做下面的工作: 1.转到特定的URL 2.在输入字段中输入一个邮政编码 3.单击提交按钮 4.解析并保存特定的div标签或重结果 - 查询页面。
我正在使用HTMLUnit和Eclipse。 我可以访问网页并通过引用表单然后输入名称在输入中输入邮编。 但是,当我尝试点击提交按钮时,我得到一个ElementNotFoundException错误。
这里的提交按钮如何在网页上实现的样本:
type="submit" value="submit" name="submit">Enter post code
这里是我的代码如下所示:
package htmlunittest;
import java.io.IOException;
import java.net.URL;
import junit.framework.TestCase;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
public class htmlunittest extends TestCase{
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception
{
final WebClient webClient = new WebClient();
final HtmlPage startPage = webClient.getPage("http://www.testpage.com");
final HtmlForm form = (HtmlForm) startPage.getForms().get(2);
final HtmlTextInput textField = form.getInputByName("address");
textField.setValueAttribute("my post code");
//throws ElementNotFoundException
final HtmlSubmitInput button = form.getInputByName("submit");
// Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
System.out.println(page2.getHtmlElementById("mainContent"));
webClient.closeAllWindows();
}
}
可有人请点我在正确的方向至于如何通过HTMLUNIT点击提交按钮?
感谢
我试图从以下网站检索商店的开放时间:http://www.tesco.com/storeLocator/一旦我输入邮政编码:SW19 8YA,那么我需要检索商店的开放时间。 –