Htmlunit button won't submit? - java

public void actionVote() {
HtmlForm form = this.page.getForms().get(0);
HtmlInput button = form.getInputByValue("vote");
try {
button.click();
} catch (IOException e) {
e.printStackTrace();
}
}
When i do println with button.asText(), it gives me the correct value of the submit button, but when I do button.click, nothing happens, like it doesn't submit the form.
I can't get the button using HtmlButton because the submit button doesn't have any id or name.
I also can't make it HtmlButton from HtmlInput.
Why doesn't this submit? Wrong element?

Try this - getInputByName or getButtonByName
HtmlForm form = this.page.getForms().get(0);
HtmlInput button = form.getInputByName("vote");
Or you can also create a fake button:
HtmlElement fakeButton = page.createElement("button");
button.setAttribute("type", "submit");
// add the button to the form
form.appendChild(fakeButton );
fakeButton.click();

Can you try below code:
HtmlForm form = page.getForms().get(0);
HtmlElement input = form.getElementsByAttribute("input", "name", "vote").get(0);
page = input.click();

Related

Htmlunit - click() doesn't work

I am spidering a web page ... but click() doesnt work, or doesn't navigate ...
Any clue what could be the issue ? I'm using 2.25 version
you can see all details in the code, thank you very much in advance.
this my code:
#Test
public String xxx() throws Exception {
try (final WebClient webClient = new WebClient(BrowserVersion.getDefault())) {
webClient.setJavaScriptTimeout(15000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setJavaScriptEnabled(false);
webClient.waitForBackgroundJavaScript(30000);
webClient.getOptions().setActiveXNative(true);
webClient.getOptions().setAppletEnabled(true);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setRedirectEnabled(true);
// add to log variable
//toLog.append(" contrato: ").append(numeroContrato);
final HtmlPage consultaCuentaPage = webClient.getPage(url);
// grab first form
final HtmlForm consultarCuentaForm = consultaCuentaPage.getForms().get(0);
// numero cuenta input
final HtmlInput numeroCuentaInput = consultarCuentaForm.getInputByName("nroCuenta");
// consultar button
final HtmlInput consultarButton = consultarCuentaForm.getInputByName("commandConsultar");
// Change the value of the text field
numeroCuentaInput.setValueAttribute("1111");
// Now submit the form by clicking the button and get back the second page.
final HtmlPage consultaCuentaPage2 = consultarButton.click();
LOG.info("time: " + consultaCuentaPage2.getWebResponse().getLoadTime());
// LOG.info("time: " + consultaCuentaPage2.getWebResponse().getContentAsString());
//System.out.println(consultaCuentaPage2.asText());
////*[#id="form"]/div[1]/fieldset/table/tbody/tr[1]/td[1]
if (consultaCuentaPage2.getFirstByXPath("//*[#id=\"form\"]/div[1]/fieldset/table/tbody/tr[1]/td[1]") != null) {
return ((HtmlTableDataCell)consultaCuentaPage2.getFirstByXPath("//*[#id=\"form\"]/div[1]/fieldset/table/tbody/tr[1]/td[1]")).asText();
}
}
return null;
}

Receiving error when Uploading File using HtmlUnit

I am currently attempting to automate the upload of a file to a specific site. I am able to successfully login to the site and navigate to the import page; however, when I attempt to import the file, I receive an error. My guess is that it is because I am simply a user and am not granted permissions to write to the server. However, if I perform the import manually, then it is successful. Normally there would be four stages to the import. However, after the first step you can see that an error occurred. My code is listed below along with the error I am receiving:
public static void main(String args[]) throws Exception {
login();
}
#SuppressWarnings("resource")
public static void login() throws Exception {
// Open the webclient using Internet Explorer (Chrome does not work).
final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER);
// Get the first page
final HtmlPage page = webClient.getPage("http://telephone.qqest.com/phone/Login/Login.asp");
// Get the form that we are dealing with.
final HtmlForm loginForm = page.getFormByName("frmLogin");
final HtmlTextInput userName = loginForm.getInputByName("Login");
final com.gargoylesoftware.htmlunit.html.HtmlPasswordInput passWord = (com.gargoylesoftware.htmlunit.html.HtmlPasswordInput)
loginForm.getInputByName("Password");
final HtmlTextInput companyID = loginForm.getInputByName("Ident");
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setRedirectEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getCookieManager().setCookiesEnabled(true);
//final HtmlInput login = loginForm.getInputByName("Login");
// Change the values of the text fields.
userName.setValueAttribute("xxxx");
passWord.setValueAttribute("xxxxx");
companyID.setValueAttribute("xxxxx");
//create a submit button - it doesn't work with 'input'
DomElement loginBtn = page.createElement("button");
loginBtn.setAttribute("type", "submit");
// append the button to the form
loginForm.appendChild(loginBtn);
// submit the form
loginBtn.click();
//navigate to page for import.
HtmlPage page3 = webClient.getPage("http://telephone.qqest.com/phone/Imports/Employee/Module.asp");
//populate the textfield with the specified file.
final HtmlForm importForm = page3.getFormByName("ImportForm");
final HtmlFileInput inputFile = importForm.getInputByName("UploadFile");
inputFile.setValueAttribute("C:\\Users\\thisFile.xls");
inputFile.click();
final HtmlSubmitInput importBtn = (HtmlSubmitInput)importForm.getInputByValue("Import");
try {
importBtn.fireEvent(Event.TYPE_INPUT);
}
catch (NullPointerException ex) {
System.err.println(ex);
}
HtmlPage page4 = webClient.getPage("http://telephone.qqest.com/phone/Imports/Employee/ImportFile.asp?FileType=application/vnd.ms-excel&FilePath=c%3A%5Cinetpub%5Cwwwroot%5Cphone%5CDownloads%5CImports%5C&FileName=thisFile.xls.asp");
System.out.println("Import Page: " + page4.asText());
}
The error I am receiving:
Stage 1 of 4: Upload File - Completed
Microsoft JET Database Engine error '80004005'
Cannot update. Database or object is read-only.
/phone/Imports/Employee/ImportFile.asp, line 155
I have figured out a solution and wanted to post it for those who might find it useful in the future. The problem was that I was simply trying to redirect to the import page by using the URL. Prior I had tried to submit the forms with an importBtn.click() statement; however, I needed to declare this statement as its own HtmlPage variable.
final HtmlSubmitInput importBtn = (HtmlSubmitInput)importForm.getInputByValue("Import");
HtmlPage page4 = importBtn.click();
// loops until the page changes.
while(page4 == page3) {
// The page hasn't changed.
Thread.sleep(500);
}
System.out.println("Import Page: " + page4.asText());

WorkbenchPage.openEditor() does nothing

I'm trying make a toolbar button to open one file with another editor on my RCP aplication!
I have de following code:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart oldEditor = page.getActiveEditor();
IFile file = ((IFileEditorInput) oldEditor.getEditorInput()).getFile();
IConfigurationElement[] editorsElements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.ui.editors");
IEditorInput editorInput = new FileEditorInput(file);
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page2 = window.getActivePage();
try {
page2.openEditor(editorInput, editorsElements[3].getAttribute("id"));
System.out.println("==>>"+editorInput+">>>>"+ editorsElements[3].getAttribute("id"));
} catch (PartInitException e) {
e.printStackTrace();
}
but when i call de action, he did not do anything! but also does not return error..
The result of System.out.println() looks like correct:
==>>org.eclipse.ui.part.FileEditorInput(/g/Network.int)>>>>DesignEditor
what i do wrong?
I following this advice to do my button
Sorry my english
Regards
The id value should be more like a java package name: org.myorg.tooling.designeditor

Problem in HtmlUnit API for Java (Headless Browser)?

I am using HtmlUnit headless browser to browse this webpage (you can see the webpage to have a better understanding of the problem).
I have set the select's value to "1"
by the following commands
final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_7);
try {
// Configuring the webClient
webClient.setJavaScriptEnabled(true);
webClient.setThrowExceptionOnScriptError(false);
webClient.setCssEnabled(true);
webClient.setUseInsecureSSL(true);
webClient.setRedirectEnabled(true);
webClient.setActiveXNative(true);
webClient.setAppletEnabled(true);
webClient.setPrintContentOnFailingStatusCode(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
// Adding listeners
webClient.addWebWindowListener(new com.gargoylesoftware.htmlunit.WebWindowListener() {
public void webWindowOpened(WebWindowEvent event) {
numberOfWebWindowOpened++;
System.out.println("Number of opened WebWindow: " + numberOfWebWindowOpened);
}
public void webWindowContentChanged(WebWindowEvent event) {
}
public void webWindowClosed(WebWindowEvent event) {
numberOfWebWindowClosed++;
System.out.println("Number of closed WebWindow: " + numberOfWebWindowClosed);
}
});
webClient.setWebConnection(new HttpWebConnection(webClient) {
public WebResponse getResponse(WebRequestSettings settings) throws IOException {
System.out.println(settings.getUrl());
return super.getResponse(settings);
}
});
CookieManager cm = new CookieManager();
webClient.setCookieManager(cm);
HtmlPage page = webClient.getPage("http://www.ticketmaster.com/event/0B004354D90759FD?artistid=1073053&majorcatid=10002&minorcatid=207");
HtmlSelect select = (HtmlSelect) page.getElementById("quantity_select");
select.setSelectedAttribute("1", true);
and then clicked on the following button
by the following commands
HtmlButtonInput button = (HtmlButtonInput) page.getElementById("find_tickets_button");
HtmlPage captchaPage = button.click();
Thread.sleep(60*1000);
System.out.println("======captcha page=======");
System.out.println(captchaPage.asXml());
but even after clicking on the button and waiting for 60 seconds through the Thread.sleep() method, I am getting the same HtmlPage.
But when I do the same thing through real browser then I get the page that contains CAPTCHA.
I think I am missing something in the htmlunit.
Q1. Why am I not getting the same page (that contains CAPTCHA) through htmlunit's browser?
The web form on that page requires the quantity_select drop-down to be filled in. You're attempting to do that in your code by assuming the drop-down is a select element. However, it's no longer a select element. Try using Firebug to inspect the drop-down and you'll see that JavaScript has replaced the select with a complex set of nested div elements.
If you figure out how to emulate each user click on the divs for that unusual drop-down then you should be able to submit the form.

HtmlUnit HtmlImageInput.click() not working?

I am kinda new to HtmlUnit and am having some trouble getting a form to submit with HtmlImageInput.click(). When I call the method, nothing seems to happen, no form submission, no round trip to the server, or anything, as far as I can tell. The method returns immediately, returning the current page.
There's no Javascript event handler attached to the image input. It's just a plain old vanilla image input, nothing special going on. The input is initially set to disabled when the page is loaded, and then gets enabled as the user interacts with certain AJAXy elements within the page. But by the time I click on the input, it has already been enabled, so I don't think it's an AJAX issue.
Anybody have an idea of what is going on? Runnable source code pasted below.
Thanks,
Matthew
import java.io.*;
import java.util.*;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import org.w3c.dom.*;
public class Test {
public static void main(String args[]) {
try {
WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_7);
webClient.setThrowExceptionOnScriptError(false);
HtmlPage page = webClient.getPage("http://us.megabus.com");
System.out.println("got the page");
HtmlForm form = page.getFormByName("ctl01");
System.out.println("got the form");
HtmlSelect select = form.getSelectByName("SearchAndBuy1$ddlLeavingFrom");
select.click();
System.out.println("clicked the select");
HtmlOption option = select.getOptionByValue("13");
option.click();
System.out.println("clicked the option...going to sleep");
try { Thread.sleep(15000); } catch(InterruptedException e) {}
select = form.getSelectByName("SearchAndBuy1$ddlTravellingTo");
select.click();
System.out.println("clicked the select 2");
option = select.getOptionByValue("37");
option.click();
System.out.println("clicked the option 2...going to sleep");
try { Thread.sleep(15000); } catch(InterruptedException e) {}
HtmlImage image = (HtmlImage)page.getElementById("SearchAndBuy1_imgOutboundDate");
image.click();
System.out.println("clicked the image");
String month = "April";
String date = "09";
HtmlTable table = (HtmlTable)page.getElementById("SearchAndBuy1_calendarOutboundDate");
HtmlTableRow row = ((HtmlTable)table.getCellAt(0, 0).getChildElements().iterator().next()).getRow(0);
String monthString = row.getCell(1).getTextContent();
monthString = monthString.substring(0, monthString.indexOf(' '));
while(!monthString.equals(month)) {
row.getCell(2).getChildElements().iterator().next().click();
System.out.println("clicked to go to the next month");
try { Thread.sleep(15000); } catch(InterruptedException e) {}
table = (HtmlTable)page.getElementById("SearchAndBuy1_calendarOutboundDate");
row = ((HtmlTable)table.getCellAt(0, 0).getChildElements().iterator().next()).getRow(0);
monthString = row.getCell(1).getTextContent();
monthString = monthString.substring(0, monthString.indexOf(' '));
}
DomNodeList<HtmlElement> aList = table.getElementsByTagName("a");
for (int i = 0; i < aList.size(); i++) {
HtmlAnchor anchor = (HtmlAnchor)aList.get(i);
if (anchor.getAttribute("title").equals(DomElement.ATTRIBUTE_NOT_DEFINED) || anchor.getAttribute("title").equals(DomElement.ATTRIBUTE_VALUE_EMPTY))
throw new RuntimeException("DomElement ATTRIBUTE_NOT_DEFINED or ATTRIBUTE_VALUE_EMPTY");
if (anchor.getAttribute("title").equals(month + " " + date)) {
anchor.click();
try { Thread.sleep(15000); } catch(InterruptedException e) {}
break;
}
}
HtmlImageInput imageInput = (HtmlImageInput)page.getElementByName("SearchAndBuy1$btnSearch");
page = (HtmlPage)imageInput.click();
System.out.println("clicked search button");
} catch(FailingHttpStatusCodeException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ElementNotFoundException e) {
e.printStackTrace();
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
That image is not an input field, it's just a plain old image:
<img id="SearchAndBuy1_imgOutboundDate" disabled="disabled" alt="calendar"
CausesValidation="False" src="images/icon_calendar.gif" style="border-width:0px;" />
There are no JS handlers specified there, so they must be attached elsewhere, and seems it's at the bottom of the page:
Sys.Application.add_init(function() {
$create(AjaxControlToolkit.PopupControlBehavior,
{"PopupControlID":"SearchAndBuy1_panelOutboundDate","Position":3,"dynamicServicePath":"/default.aspx","id":"SearchAndBuy1_pceImageOutboundDate"}, null, null, $get("SearchAndBuy1_imgOutboundDate"));
});
When your program clicks on the image, there is no form submit, just an AJAX call (presumably), so you're right, you don't get a new page back. But as your code proves (I just ran it with a debugger), the content of the HtmlPage has changed, since it now contains the calendar widget, which you were able to pull details from.
It can be a bit confusing knowing when you will get a net new HtmlPage back, but usually it's only when you would see a whole new page in the browser. I've never tried HtmlUnit against something like Gmail, but I suspect you might only ever deal with the one HtmlPage object, and everything takes places within it.

Categories

Resources