【问题标题】:Java and HTMLUnit: How to click on submit button?Java 和 HTMLUnit:如何点击提交按钮?
【发布时间】:2013-04-10 07:17:06
【问题描述】:

我是 Java 新手,需要编写各种 Java 应用程序来进行网页抓取和网页交互。

我开始使用 Selenium,但因为它直接与浏览器交互,所以不适合我使用。

我需要完成以下任务: 1. 转到特定的 URL 2. 在输入字段中输入邮政编码 3.点击提交按钮 4. 解析并保存特定div标签或重新查询页面的结果。

我正在使用 HTMLUnit 和 Eclipse。 我可以通过引用表单和输入名称来访问网页并在输入中输入邮政编码。 但是,当我尝试单击提交按钮时,出现 ElementNotFoundException 错误。

下面是提交按钮在页面上的实现示例:

type="submit" value="submit" name="submit">输入邮编

我的代码如下所示:

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 点击提交按钮的正确方向?

谢谢

【问题讨论】:

    标签: java eclipse htmlunit submit-button


    【解决方案1】:

    如果没有您尝试获取的整个页面,很难找出为什么它不起作用。

    我敢打赌,您没有使用.get(2) 获取正确的表单,顺便说一句,以这种方式获取表单通常是一个坏主意,因为如果目标页面稍微更改其源代码只是为了在其上方添加一个表单一个你的刮刀将不再工作,因为索引会不同。

    【讨论】:

    • 我正在尝试从以下站点检索商店营业时间:tesco.com/storeLocator 输入邮政编码后:SW19 8YA 然后我需要检索商店营业时间。
    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多