try { HtmlPage page = webClient.getPage("http://www.w3schools.com/HTML/tryit.asp?filename=tryhtml_noframes"); HtmlInlineFrame frame = page.getFirstByXPath("//iframe[@name='view']"); page = webClient.getPage(page.getFullyQualifiedUrl(frame.getSrcAttribute())); System.out.println(page.asXml()); } catch (Exception e) { e.printStackTrace(); }
public static void main(String[] args) { String baseUrl = "https://news.ycombinator.com" ; String loginUrl = baseUrl + "/login?goto=news" ; String login = "login"; String password = "password" ; try { System.out.println("Starting autoLogin on " + loginUrl); WebClient client = autoLogin(loginUrl, login, password); HtmlPage page = client.getPage(baseUrl) ; HtmlAnchor logoutLink = page.getFirstByXPath(String.format("//a[@href='user?id=%s']", login)) ; if(logoutLink != null ){ System.out.println("Successfuly logged in !"); // printing the cookies for(Cookie cookie : client.getCookieManager().getCookies()){ System.out.println(cookie.toString()); } }else{ System.err.println("Wrong credentials"); } } catch (Exception e) { e.printStackTrace(); } }
public WebElement findElementByXPath(String selector) { if (!(lastPage() instanceof HtmlPage)) throw new IllegalStateException("Cannot find element by xpath for " + lastPage()); Object node = ((HtmlPage) lastPage()).getFirstByXPath(selector); if (node == null) throw new NoSuchElementException("Cannot locate a node using " + selector); if (node instanceof HtmlElement) return newHtmlUnitWebElement((HtmlElement) node); throw new NoSuchElementException(String.format("Cannot find element with xpath %s", selector)); }
import java.net.URL; import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.*; public class HtmlUnitAnchorExample { public static void main(String[] args) throws Exception { String html = "<html><head><title>HTMLUNIT TEST</title></head><body>" + "" + "<span class=\"followButtonActions\" id=\".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1]. [1].[1]\"> "+ " <a class=\"Button FollowButton followButtonFollow\" role=\"button\" href=\"javascript:;\" id=\".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0\"> "+ " <span id=\".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0]\"> "+ " <span id=\".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0].[0]\">Follow</span> </span> "+ " </a> "+ "</span>" + "</body></html>"; WebClient client = new WebClient(); HtmlPage page = HTMLParser.parseHtml(new StringWebResponse(html, new URL("http://example.com")), client.getCurrentWindow()); System.out.println("Page title: "+page.getTitleText()); final HtmlAnchor myAnchor = page.getFirstByXPath("//a[@id='.reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0']"); System.out.println("Anchor found: "+myAnchor ); final HtmlPage newPage = myAnchor .click(); System.out.println("newPage: "+newPage); client.closeAllWindows(); } }
ArrayList<String> colNames = new ArrayList<>(); HtmlTable table = p.getFirstByXPath("//table"); if (table == null) return list;
HtmlTable billsTable = (HtmlTable) page.getFirstByXPath("//table[@class='listing Billing--history']"); for(HtmlTableRow row : billsTable.getBodies().get(0).getRows()){
final HtmlDivision div = authPage.getFirstByXPath("//div[@role='alert']"); if (div != null) { throw new IllegalArgumentException("Error authorizing application: " + div.getTextContent());
import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.*; public class HtmlUnitFormExample { public static void main(String[] args) throws Exception { WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage("http://www.google.com"); HtmlInput searchBox = page.getElementByName("q"); searchBox.setValueAttribute("htmlunit"); HtmlSubmitInput googleSearchSubmitButton = page.getElementByName("btnG"); // sometimes it's "btnK" page=googleSearchSubmitButton.click(); HtmlDivision resultStatsDiv = page.getFirstByXPath("//div[@id='resultStats']"); System.out.println(resultStatsDiv.asText()); // About 301,000 results webClient.closeAllWindows(); } }
import com.gargoylesoftware.htmlunit.*; import com.gargoylesoftware.htmlunit.html.*; public class HtmlUnitFormExample { public static void main(String[] args) throws Exception { WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage("http://www.google.com"); HtmlInput searchBox = page.getElementByName("q"); searchBox.setValueAttribute("htmlunit"); HtmlSubmitInput googleSearchSubmitButton = page.getElementByName("btnG"); // sometimes it's "btnK" page=googleSearchSubmitButton.click(); HtmlDivision resultStatsDiv = page.getFirstByXPath("//div[@id='resultStats']"); System.out.println(resultStatsDiv.asText()); // About 309,000 results webClient.closeAllWindows(); } }
void assertTestResultsAsExpected(WebClient wc, Run run, String restOfUrl, String packageName, String expectedResult, String expectedDurationStr, int expectedTotalTests, int expectedTotalDiff, int expectedFailCount, int expectedFailDiff, int expectedSkipCount, int expectedSkipDiff) throws IOException, SAXException { // TODO: verify expectedResult // TODO: verify expectedDuration XmlPage xmlPage = wc.goToXml(run.getUrl() + restOfUrl + "/" + packageName + "/api/xml"); int expectedPassCount = expectedTotalTests - expectedFailCount - expectedSkipCount; // Verify xml results rule.assertXPathValue(xmlPage, "/packageResult/failCount", Integer.toString(expectedFailCount)); rule.assertXPathValue(xmlPage, "/packageResult/skipCount", Integer.toString(expectedSkipCount)); rule.assertXPathValue(xmlPage, "/packageResult/passCount", Integer.toString(expectedPassCount)); rule.assertXPathValue(xmlPage, "/packageResult/name", packageName); // TODO: verify html results HtmlPage testResultPage = wc.getPage(run, restOfUrl); // Verify inter-build diffs in html table String xpathToFailDiff = "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[4]"; String xpathToSkipDiff = "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[6]"; String xpathToTotalDiff = "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[last()]"; Object totalDiffObj = testResultPage.getFirstByXPath(xpathToTotalDiff); assertPaneDiffText("total diff", expectedTotalDiff, totalDiffObj); Object failDiffObj = testResultPage.getFirstByXPath(xpathToFailDiff); assertPaneDiffText("failure diff", expectedFailDiff, failDiffObj); Object skipDiffObj = testResultPage.getFirstByXPath(xpathToSkipDiff); assertPaneDiffText("skip diff", expectedSkipDiff, skipDiffObj); // TODO: The link in the table for each of the three packages in the testReport table should link to a by-package page, // TODO: for example, http://localhost:8080/job/breakable/lastBuild/testReport/com.yahoo.breakable.misc/ }
/** * Validate CSS styles present to prevent duration text from wrapping */ @Issue("JENKINS-24352") @Test public void testDurationStyle() throws Exception { AbstractBuild b = configureTestBuild("render-test"); JenkinsRule.WebClient wc = j.createWebClient(); wc.setAlertHandler(new AlertHandler() { @Override public void handleAlert(Page page, String message) { throw new AssertionError(); } }); HtmlPage pg = wc.getPage(b, "testReport"); // these are from the test result file: String duration14sec = Util.getTimeSpanString((long) (14.398 * 1000)); String duration3_3sec = Util.getTimeSpanString((long) (3.377 * 1000)); String duration2_5sec = Util.getTimeSpanString((long) (2.502 * 1000)); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]")); pg = wc.getPage(b, "testReport/org.twia.vendor"); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]")); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration14sec + "')][contains(@class,'no-wrap')]")); pg = wc.getPage(b, "testReport/org.twia.vendor/VendorManagerTest"); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration2_5sec + "')][contains(@class,'no-wrap')]")); }
public static WebClient autoLogin(String loginUrl, String login, String password) throws FailingHttpStatusCodeException, MalformedURLException, IOException{ WebClient client = new WebClient(); client.getOptions().setCssEnabled(false); client.getOptions().setJavaScriptEnabled(false); HtmlPage page = client.getPage(loginUrl); HtmlInput inputPassword = page.getFirstByXPath("//input[@type='password']"); //The first preceding input that is not hidden HtmlInput inputLogin = inputPassword.getFirstByXPath(".//preceding::input[not(@type='hidden')]"); inputLogin.setValueAttribute(login); inputPassword.setValueAttribute(password); //get the enclosing form HtmlForm loginForm = inputPassword.getEnclosingForm() ; //submit the form page = client.getPage(loginForm.getWebRequest(null)); //returns the cookies filled client :) return client; }
Object imageNode = projectPage.getFirstByXPath("//img[@src='test/trend']"); assertNotNull("couldn't find any matching nodes", imageNode); assertTrue("image node should be an HtmlImage object", imageNode instanceof HtmlImage);