problem writing HTMLUnit script for YUI form submit - forms
I want to write a simple HTMLUnit test script for Jenkins (former Hudson). INFO: Jenkins uses the YUI Javascript library. The YUI library replaces the form submit with a custom button. The script just creates a new job in Jenkins.
start Jenkins:
java -jar jenkins.war
Current versions of HTMLUnit do not support form.submit any more and require you to use button.click() for form submitting. Unfortunately this does not work for Jenkins (the sample below does not advance the page and create the job but stays on the new job page)
I tried for some hours now to find a solution or workaround but so far I could not get the form submitted. Hopefully somebody has found a solution and let me know.
Here is my sample code:
package example;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
public class jenkins3 {
public static void main(String args[]) {
// create a new job in jenkins
// home
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
try {
final HtmlPage page1 = webClient.getPage("http://localhost:8080");
//assertEquals("Dashboard [Jenkins]", page1.getTitleText());
// new job
final HtmlAnchor new_job = page1.getAnchorByText("New Job");
final HtmlPage page2 = new_job.click();
// job name
HtmlTextInput name_field = (HtmlTextInput) page2.getElementById("name");
name_field.type("new job by htmlunit");
// radio button
final HtmlInput radio_freestyle = (HtmlInput) page2.getByXPath("//input[#value='hudson.model.FreeStyleProject']").get(0);
radio_freestyle.click();
Thread.sleep(10000);
// OK button (submit form)
final HtmlForm form = page2.getFormByName("createItem");
//final HtmlSubmitInput button = (HtmlSubmitInput) form.getByXPath("//button").get(0);
final HtmlButton button = (HtmlButton) form.getByXPath("//button").get(0);
final HtmlPage page3 = button.click(); // !!!!! Form submit does not workstacko
//assertEquals("Dashboard [Jenkins]", page3.getTitleText());
}
catch( Exception e ) {
System.out.println( "General exception thrown:" + e.getMessage() );
e.printStackTrace();
}
webClient.closeAllWindows();
}
}
Although this may be completely out of the question in your senerio: i would suggest giving up on HTMLUnit. I've had bug after bug, mainly because of the pages I've been automating tests for aren't always 100% valid html (3rd party piggybacked requests). I finally went looking elsewhere and found PhantomJS (js bindings to the WebKit engine) much better suited.
For me the advantages were evident:
- no need for another app server
- much simpler and faster to script JS than Java
- a "real"-world engine is more realistic than a buggy emulator one
Thats my advice,
Cheers
HTMLUnit doesn't include support for testing javascript actions. You might not want to switch your testing framework at this point, but I would recommend using Selenium for this kind of testing. It runs a mock browser and executes javascript, making it possible to do this sort of thing.
I have found this little trick to work. Navigate to the Jenkins login page using HtmlUnit. Add a Submit button to the login form. Set appropriate attributes to Submit element, including an "onclick" value. Click on this new button and viola! You're logged in.
Note, if you're not concerned about security, you can also do this:
webClient.getPage("https://yourdomain:8443/jenkins/j_acegi_security_check?j_username=yourUsername&j_password=yourPassword");
See below for first method.
Enjoy,
Nick.
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class JenkinsLogin {
final String urlValue = "https://<yourdomain>:8443/jenkins";
private final String userName = "yourUsername";
private final String password = "yourPassword";
protected static final BrowserVersion BROWSER_VERSION_FIREFOX = new BrowserVersion(
"Netscape", "5.0 (Windows)",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0",
(float) 1.2);
private final WebClient webClient = new WebClient(BROWSER_VERSION_FIREFOX);
public static void main(final String[] args) throws Exception {
final JenkinsLogin jenkinsLogin = new JenkinsLogin();
jenkinsLogin.login();
}
private void login() throws Exception {
this.webClient.setThrowExceptionOnScriptError(false);
HtmlPage page = this.webClient.getPage(this.urlValue + "/login");
final HtmlForm form = page.getFormByName("login");
form.getInputByName("j_username").setValueAttribute(this.userName);
form.getInputByName("j_password").setValueAttribute(this.password);
final HtmlElement createdElement = page.createElement("input");
createdElement.setAttribute("type", "submit");
createdElement.setAttribute("name", "submitIt");
createdElement.setAttribute("onclick", "login.submit();");
form.appendChild(createdElement);
final HtmlElement submitButton = form.getInputByName("submitIt");
page = submitButton.click();
final HtmlElement loginField = page.getFirstByXPath("id('login-field')");
if (loginField == null || !loginField.getTextContent().contains(this.userName))
throw new RuntimeException("Unable to log on to Jenkins. ");
System.out.println("Logged in! ");
}
}
Does replacing
final HtmlButton button = (HtmlButton) form.getByXPath("//button").get(0);
final HtmlPage page3 = button.click()
with
form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button")));
work?
Related
Why isn't Gtk Filechooser Button selecting any file in my flatpak build?
I have a file chooser button that triggers a change in the titlebar whenever a file is selected with it. And it seems to work fine in my non-flatpak build. import gtk.Application : Application; import gtk.ApplicationWindow : ApplicationWindow; import gio.Application : GioApp = Application; import gtkc.gtktypes : GApplicationFlags, FileChooserAction; import gtk.FileChooserButton : FileChooserButton; const string AppID = `org.github.flatfcbtest`; int main(string[] args) { auto app = new App(); return app.run(args); } public class App : Application { public: this(const string appID = AppID, const GApplicationFlags flags = GApplicationFlags.FLAGS_NONE) { super(appID, flags); addOnActivate(delegate void(GioApp _) { auto pw = new PrimaryWindow(this); pw.showAll(); }); } } class PrimaryWindow : ApplicationWindow { this(Application app) { super(app); setSizeRequest(500, 300); auto fcb = new FileChooserButton(`Select file`, FileChooserAction.OPEN); fcb.addOnFileSet(delegate void (FileChooserButton _) { setTitle(`file set!`); }); add(fcb); } } (GtkD reference) However in my flatpak builds, the file selected with the chooser button does not select anything and it keeps saying (None). However my titlebar is changes accordingly so I know that the signal was emitted by the file chooser button. Here is my flatpak permissions list: finish-args: - --socket=fallback-x11 - --share=ipc - --filesystem=host - --device=all - --socket=session-bus What's causing this?
Typically if you're shipping a flatpak, you want to avoid --filesystem=host and just use GtkFileChooserNative instead. This class supports portals, allowing a user to select files the application does not have permission to access by itself. This is a much better approach than giving the application full filesystem access. GtkFileChooserNative will still work in a non-flatpak application and you shouldn't notice any difference unless you're doing something fancy. As for your question of why GtkFileChooser is not working with --filesystem=host however, I do not know.
Execute javascript when clicking on a wicket Resource Link
I have a wicket Resource link that generates and downloads a pdf file when Clicking on it. ResourceLink pdfResourceLink = new ResourceLink("dlPdf", new PdfResource() { private static final long serialVersionUID = 1L; #Override public byte[] getPdf() { //code for generating pdf content } #Override public String getFilename() { return "file.pdf"; } }); I want to block the page during the file generation to prevent user from doing any action. Is there a way to execute Javascript when clicking on a Resource Link ?
This is possible with the new AjaxDownload behavior that we are going to introduce in 7.7.0. The JIRA ticket is WICKET-6286 (I'm on my mobile so I might be wrong. Google it !). You can copy the code locally until it is officially released. See AjaxDownloadPage.java in wicket-examples for demo.
trying to generate automated login java code
I have been trying to build a java program to perform automatic login to a web page but i am using the code below import java.util.*; import java.net.*; import java.io.*; import java.applet.*; class main { public static void main(String args[]) throws Exception{ final WebClient webClient = new WebClient(); // Fake page final HtmlPage page1 = webClient.getPage("https://example/login.php"); // 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("login_form"); final HtmlSubmitInput button = form.getInputByName("Submit"); final HtmlTextInput username = form.getInputByName("username"); final HtmlTextInput psswd = form.getInputByName("password"); // Fake username and password username.setValueAttribute("username"); psswd.setValueAttribute("password"); // Now submit the form by clicking the button and get back the second page. final HtmlPage page2 = button.click(); } } but i had been getting the error WebClient not found, HTMLUnit not found. Iam not using eclipse or any other kind similar to it. I am using Sublime text3 for writting the java code. Provide me with the correct import package to remove the errors. I had search the internet for this and had already downloaded HTMLUNIt packages from internet and put them in my enivronment path variable.
How to write selenium webdriver automation script for Facebook logout?
I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help. public class fb { public static void main(String args[]) { WebDriver driver = new FirefoxDriver(); driver.get("https://facebook.com"); driver.manage().window().maximize(); driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email"); driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password"); driver.findElement(By.xpath(".//*[#id='u_0_n']")).click(); driver.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click(); driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.
Automation Script for FaceBook Login and logout: WebDriver driver = new FirefoxDriver(); driver.get("https://www.facebook.com/"); driver.manage().window().maximize(); driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email"); driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password"); //click for login driver.findElement(By.xpath("//label[#id='loginbutton']/input")).click(); //Mouse over on logOut drop down menu icon,then click logout WebElement mouseOverEle = driver.findElement(By.id("pageLoginAnchor")); Actions actions = new Actions(driver); actions.moveToElement(mouseOverEle).click().perform(); //click for logout driver.findElement(By.xpath("//input[#value='Log Out']")).click();
Try Using the below code to click on the log out button //wait for the userNavigationLabel to load fully any wait techniques implicit or explicit for sample i have used Thread.sleep although it is not recommended Thread.sleep(3000); JavascriptExecutor js = (JavascriptExecutor) driver; String script = "var forms = document.getElementsByTagName('form');for (var i = 0; i < forms.length; i++) { if(forms[i].getAttribute('action')=='https://www.facebook.com/logout.php'){forms[i].submit();}}"; js.executeScript(script); In the above code i have used javascript to click on the logout button...i tested it on the browser console it is working fine Hope this helps you.....Kindly get back if you have any queries
try: lsb=browser.find_element_by_xpath('//*[#id="pageLoginAnchor"]') lsb.click() time.sleep(5) mlb=browser.find_element_by_xpath('//*[#id="u_d_3"]/div/div/div[1]/div/div/ul/li[16]') time.sleep(2) mlb.click() inputElement33 = browser.find_element_by_name('pass').is_displayed() print("Looged out") except: print("Cannot logout")
// Enter you Email id dr.findElement(By.xpath(".//*[#id='email']")).sendKeys("YorEmailID"); // Enter you Password dr.findElement(By.xpath(".//*[#id='pass']")).sendKeys("YourPassword"); //click for login dr.findElement(By.xpath("//label[#id='loginbutton']/input")).click(); dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // Click for Alert dr.findElement(By.className("_3ixn")).click(); //Click for Navigation Label dr.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click(); dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Click for Lout Button dr.findElement(By.xpath("//a[contains(#data-gt,'menu_logout')]")).click();
Replace your logout button click with this. //Wait for button appear WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4)); wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']"))); //Click it by xpath driver.FindElement(By.XPath("//a[.='Log out']")).Click(); Or: //Wait for button appear WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4)); wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']"))); //Click it by JS IJavaScriptExecutor js = ((IJavaScriptExecutor)driver); IWebElement logout = driver.FindElement(By.XPath("//a[.='Log out']")); js.ExecuteScript("arguments[0].click();", logout); 100% worked
**#Working script** **#firefox can be used too instead of chrome** **#sleep is necessary to give sufficient loading time** from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException usr=input('Enter Email Id:') pwd=input('Enter Password:') driver = webdriver.Chrome() driver.get('https://www.facebook.com/') a = driver.find_element_by_id('email') a.send_keys(usr) b = driver.find_element_by_id('pass') b.send_keys(pwd) c = driver.find_element_by_id('loginbutton') c.click() sleep(20) d= driver.find_element_by_id("userNavigationLabel") d.click() sleep(10) e=driver.find_element_by_xpath("//a[contains(#data-gt,'menu_logout')]") e.click() sleep(5) driver.quit()
There are duplicate objects in the Home page.Hence, to avoid confusion,Xpath can be written in combination of class names, which in our case is, //div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li Get the maximum number of <li> tags in the <ul> as follows , List<WebElement> li = driver.findElements(By.xpath("//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li")); System.out.println("Size:"+li.size()); The Log out button will always be the last option, inspite of any changes to the list , hence append the last index to the xpath and click on it , String logOutBtn = "//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li[" + li.size() + "]"; driver.findElement(By.xpath(logOutBtn)).click(); -- Clicking on log out button Hope this helps ! Thank you ..
package package1; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class class1 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\CloudLogic.Tech01\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver drr = new ChromeDriver(); drr.get("https://www.facebook.com/"); drr.findElement(By.id("email")).sendKeys("emailId"); drr.findElement(By.id("pass")).sendKeys("********"); drr.findElement(By.xpath("//label[#id='loginbutton']")).click(); } }
upgrade from wicket 1.4.9 to wicket 1.4.22 causes button to not be triggered
We are using 1.4.9 for our current webapp. But we want to upgrade to higher 1.4.x version preferably 1.4.22(latest 1.4). The problem is that the page won't submit if AjaxButton is clicked. This is working in 1.4.9. I put breakpoint on the onSubmit of that button but it is not going there. Any insights on this? Thanks! Here is the code: For the button: public abstract class SXIButton extends AjaxButton { public SXIButton(String id, Form form) { super(id, form); initialize(); add(new SimpleAttributeModifier("validating", "false")); } } In the java: searchForm.add(new SXIButton("searchButton", searchForm) { private static final long serialVersionUID = -4366670520053224476L; #Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { LOG.info("Searching Users"); target.addComponent(userContainer); userSearchModel.setUserCurrentUserFilter(getSessionBOUser().getCd()); UserDataProvider udp = new UserDataProvider(userSearchModel,isForSearch); udp.setSort("cd", true); userContainer.addOrReplace(getResultPanel(udp)); } }); add(portlet); portlet.add(searchForm); in html <input type = "submit" wicket:id = "searchButton" wicket:message="value:button.search" />
Without any code it's hard to help you out. I would first check the changelog to see if anything was changed in a later version that might causes you trouble (e.g. this ticket). If you cannot find anything obvious you might want to update first to another version which is not the latest one, to narrow down in which version your code breaks for the first time. But those are just shots in the dark.