示例#1
0
  /**
   * Resets this form to its initial values, returning the page contained by this form's window
   * after the reset. Note that the returned page may or may not be the same as the original page,
   * based on JavaScript event handlers, etc.
   *
   * @return the page contained by this form's window after the reset
   */
  public Page reset() {
    final SgmlPage htmlPage = getPage();
    final ScriptResult scriptResult = fireEvent(Event.TYPE_RESET);
    if (ScriptResult.isFalse(scriptResult)) {
      return scriptResult.getNewPage();
    }

    for (final HtmlElement next : getHtmlElementDescendants()) {
      if (next instanceof SubmittableElement) {
        ((SubmittableElement) next).reset();
      }
    }

    return htmlPage;
  }
示例#2
0
 /**
  * Returns <tt>true</tt> if this event has been aborted via <tt>preventDefault()</tt> in
  * standards-compliant browsers, or via the event's <tt>returnValue</tt> property in IE, or by the
  * event handler returning <tt>false</tt>.
  *
  * @param result the event handler result (if <tt>false</tt>, the event is considered aborted)
  * @return <tt>true</tt> if this event has been aborted
  */
 public boolean isAborted(final ScriptResult result) {
   final boolean checkReturnValue =
       getBrowserVersion().hasFeature(JS_EVENT_ABORTED_BY_RETURN_VALUE_FALSE);
   return ScriptResult.isFalse(result)
       || (!checkReturnValue && preventDefault_)
       || (checkReturnValue && Boolean.FALSE.equals(returnValue_));
 }
示例#3
0
  /**
   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN
   * RISK.</span><br>
   *
   * <p>Submits this form to the server. If <tt>submitElement</tt> is <tt>null</tt>, then the
   * submission is treated as if it was triggered by JavaScript, and the <tt>onsubmit</tt> handler
   * will not be executed.
   *
   * <p><b>IMPORTANT:</b> Using this method directly is not the preferred way of submitting forms.
   * Most consumers should emulate the user's actions instead, probably by using something like
   * {@link HtmlElement#click()} or {@link HtmlElement#dblClick()}.
   *
   * @param submitElement the element that caused the submit to occur
   * @return a new page that reflects the results of this submission
   */
  Page submit(final SubmittableElement submitElement) {
    final HtmlPage htmlPage = (HtmlPage) getPage();
    final WebClient webClient = htmlPage.getWebClient();
    if (webClient.getOptions().isJavaScriptEnabled()) {
      if (submitElement != null) {
        isPreventDefault_ = false;
        final ScriptResult scriptResult = fireEvent(Event.TYPE_SUBMIT);
        if (isPreventDefault_) {
          // null means 'nothing executed'
          if (scriptResult == null) {
            return htmlPage;
          }
          return scriptResult.getNewPage();
        }
      }

      final String action = getActionAttribute().trim();
      if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        return htmlPage
            .executeJavaScriptIfPossible(action, "Form action", getStartLineNumber())
            .getNewPage();
      }
    } else {
      if (StringUtils.startsWithIgnoreCase(
          getActionAttribute(), JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        // The action is JavaScript but JavaScript isn't enabled.
        // Return the current page.
        return htmlPage;
      }
    }

    final WebRequest request = getWebRequest(submitElement);
    final String target = htmlPage.getResolvedTarget(getTargetAttribute());

    final WebWindow webWindow = htmlPage.getEnclosingWindow();
    webClient.download(webWindow, target, request, false, "JS form.submit()");
    return htmlPage;
  }
示例#4
0
  public static void main(String[] args) throws Exception {
    // Create and initialize WebClient object
    // Create and initialize WebClient object
    String dualPwd = "xxxxxx";
    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_38);
    // webClient.throwFailingHttpStatusCodeExceptionIfNecessary(webResponse);

    // visit Yahoo Mail login page and get the Form object
    HtmlPage page =
        (HtmlPage)
            webClient.getPage(
                "https://www.ebanking.hsbc.com.hk/1/2/logon?LANGTAG=en&COUNTRYTAG=US");
    HtmlForm form = page.getFormByName("User");

    // Enter login and passwd
    form.getInputByName("u_UserID").setValueAttribute("charlieskc");
    page = (HtmlPage) form.getInputByValue("press").setValueAttribute("click");
    List<HtmlAnchor> anchorList = page.getAnchors();
    for (HtmlAnchor anchor : anchorList) {
      if (anchor
          .getOnClickAttribute()
          .equals(
              "document.getElementById('submittype').value = 'click';PC_7_0G3UNU10SD0MHTI7TQA0000000000000_selectLogonMode(0)")) {
        System.out.println(anchor.getHrefAttribute());
        System.out.println(anchor.getOnClickAttribute());
        page = anchor.click();
        // System.out.println(page.asXml());
      }
    }

    HtmlForm passwordform = page.getFormByName("PC_7_0G3UNU10SD0MHTI7EMA0000000000000_pwd");
    passwordform.getInputByName("memorableAnswer").setValueAttribute("z0226409");

    HtmlForm secondPasswordform =
        page.getFormByName("PC_7_0G3UNU10SD0MHTI7EMA0000000000000_2ndpwd");
    // secondPasswordform.getInputByName("memorableAnswer").setValueAttribute("z0226409");

    HtmlTable table = getTableFromDomElement(secondPasswordform);

    System.out.println("Table xml" + table.asXml());

    for (HtmlElement element : secondPasswordform.getHtmlElementDescendants()) {
      // System.out.println(element.asXml());
    }

    ScriptResult result =
        page.executeJavaScript("PC_7_0G3UNU10SD0MHTI7TQA0000000000000_selectLogonMode(0)");
    page = (HtmlPage) result.getNewPage();

    // System.out.println("result: "+ result);

    // System.out.println("result: " + page.asXml());

    // form.getInputByName("logonMode").setValueAttribute("charlieskc");
    // form.getInputByName("passwd").setValueAttribute("@@@@@@@");

    // Click "Sign In" button/link

    // Click "Inbox" link
    HtmlAnchor anchor = (HtmlAnchor) page.getHtmlElementById("WelcomeInboxFolderLink");
    page = (HtmlPage) anchor.click();

    // Get the table object containing the mails
    HtmlTable dataTable = (HtmlTable) page.getHtmlElementById("datatable");

    // Go through each row and count the row with class=msgnew
    int newMessageCount = 0;
    List<HtmlTableRow> rows = (List) dataTable.getHtmlElementsByTagName("tr");
    for (HtmlTableRow row : rows) {
      if (row.getAttribute("class").equals("msgnew")) {
        newMessageCount++;
      }
    }

    // Print the newMessageCount to screen
    System.out.println("newMessageCount = " + newMessageCount);

    // System.out.println(page.asXml());
  }
示例#5
0
  public void initCookie() {

    // try {
    // System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");
    // driver = new ChromeDriver();
    // driver.get("http://weibo.com/");
    // WebElement e = driver.findElement(By.name("username"));
    // e.sendKeys(account.getUsername());
    // e = driver.findElement(By.name("password"));
    // e.sendKeys(account.getPassword());
    // e = driver.findElement(By
    // .xpath("//span[@node-type='submitStates']"));
    // e.click();
    // Set<Cookie> cookies = driver.manage().getCookies();
    // // httpClient.startSession(new URL("http://weibo.com"));
    // HttpState state = new HttpState();
    // String ck = "";
    // for (Cookie c : cookies) {
    // ck += c.getName() + "=" + c.getValue() + "; ";
    // }
    // account.setCookie(ck);
    // driver.close();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    try {
      HttpClient httpClient = new HttpClient();
      httpClient.setTimeout(30000);
      HostConfiguration conf = new HostConfiguration();
      conf.setHost(new URI("http://www.weibo.com"));
      httpClient.setHostConfiguration(conf);
      httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
      httpClient.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
      httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
      GetMethod method =
          new GetMethod(
              "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.11)&_=1387711657507");
      httpClient.executeMethod(method);
      String s = method.getResponseBodyAsString();
      int idx;
      idx = s.indexOf("servertime\":") + "servertime\":".length();
      String servertime = s.substring(idx, s.indexOf(",", idx));
      idx = s.indexOf("nonce\":\"") + "nonce\":\"".length();
      String nonce = s.substring(idx, s.indexOf("\"", idx));
      idx = s.indexOf("pubkey\":\"") + "pubkey\":\"".length();
      String pubkey = s.substring(idx, s.indexOf("\"", idx));
      idx = s.indexOf("rsakv\":\"") + "rsakv\":\"".length();
      String rsakv = s.substring(idx, s.indexOf("\"", idx));
      PostMethod post =
          new PostMethod("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.11)");

      final WebClient webClient = new WebClient();
      HtmlPage page = webClient.getPage("http://www.baidu.com/");
      InputStream is = Testweibo.class.getClassLoader().getResourceAsStream("weibo.js");
      String script = IOUtils.toString(is);
      is.close();
      ScriptResult sr = page.executeJavaScript(script);
      script =
          "sinaSSOController.rsaPubkey = '"
              + pubkey
              + "';sinaSSOController.servertime = '"
              + servertime
              + "';sinaSSOController.nonce = '"
              + nonce
              + "';sinaSSOController.rsakv = '"
              + rsakv
              + "';sinaSSOController.from = 'weibo';sinaSSOController.useTicket = 1;";
      sr = page.executeJavaScript(script);
      script =
          "sinaSSOController.login('"
              + account.getUsername()
              + "','"
              + account.getPassword()
              + "',7);";
      sr = page.executeJavaScript(script);
      NativeObject no = (NativeObject) sr.getJavaScriptResult();

      for (Object o : no.getAllIds()) {
        // System.out.println(o + "=>" + no.get(o));
        post.setParameter(o + "", no.get(o) + "");
      }
      webClient.closeAllWindows();
      post.setParameter("gateway", "1");
      post.setParameter("savestate", "7");
      post.setParameter("useticket", "1");
      post.setParameter(
          "pagerefer",
          "http://login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D%252F");
      post.setParameter("vsnf", "1");
      post.setParameter("encoding", "UTF-8");
      post.setParameter("prelt", "140");
      post.setParameter(
          "url",
          "http://www.weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack");
      post.setParameter("returntype", "META");
      httpClient.executeMethod(post);
      s = new String(post.getResponseBody(), "UTF-8");
      idx = s.indexOf("location.replace('") + "location.replace('".length();
      String url = s.substring(idx, s.indexOf("'", idx));
      //			System.out.println(url);
      logger.debug(url);
      method = new GetMethod(url);
      httpClient.executeMethod(method);
      ;
      //			System.out.println(method.getResponseBodyAsString());
      logger.debug(method.getResponseBodyAsString());
      //			 method = new GetMethod("http://weibo.com/");
      //			 httpClient.executeMethod(method);
      //			 System.out.println(method.getURI());
      //			 System.out.println(new String(method.getResponseBody(),"UTF-8"));

      //			String ck = "";
      //			for (Cookie c : httpClient.getState().getCookies()) {
      ////				if(c.getDomain().equals(".weibo.com")||c.getDomain().equals("weibo.com"))
      //				ck += c.getName() + "=" + c.getValue() + "; ";
      //			}
      //			account.setCookie(ck);
      clientMap.put(account.getUsername(), httpClient);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }