使用Selenium或HtmlUnit执行Javascript

时间:2015-08-26 14:19:05

标签: selenium htmlunit

我需要一点帮助。

我想使用Java和Selenium或HtmlUnit打开一些页面,打开此页面后执行类似Ajax的URL并获取String响应。

假设想要打开http://www.somepage.com,当驱动程序仍在此页面上时,执行GET http://www.somepage.com/myAjax/xyz,它应返回JSON。

然后我想得到JSON响应并用它做点什么。

你能帮我,怎么做?

祝你好运

1 个答案:

答案 0 :(得分:0)

  1. 要注入自己的javascript,您可以执行以下操作:
  2. $(document).ready(function(){
        $('.project-container').mouseover(function(){
            $('.project-container__text', this)
                .addClass('project-display')
                .slideUp();
        });
    });
    
    1. 要检索javascript变量的值:
    2.         new WebConnectionWrapper(webClient) {
      
                  public WebResponse getResponse(WebRequest request) throws IOException {
                      WebResponse response = super.getResponse(request);
                      if (request.getUrl().toExternalForm().contains("my_url")) {
                          String content = response.getContentAsString("UTF-8");
      
                          // inject the below to the 'content' 
      
                          String tobeInjected = ""
                                  + "<script>\n"
                                  + "var myOwnVariable;\n"
                                  + "var xmlhttp;\n"
                                  + "if (window.XMLHttpRequest) {\n"
                                  + "  xmlhttp=new XMLHttpRequest();\n"
                                  + "}\n"
                                  + "else {\n"
                                  + "  xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');\n"
                                  + "}\n"
                                  + "\n"
                                  + "xmlhttp.onreadystatechange=function() {\n"
                                  + "  if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n"
                                  + "    myOwnVariable = xmlhttp.responseText;\n"
                                  + "  }\n"
                                  + "}\n"
                                  + "\n"
                                  + "xmlhttp.open('GET', 'http://www.somepage.com/myAjax/xyz', true);\n"
                                  + "xmlhttp.send();\n"
                                  + "</script>";
      
                          WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
                                  response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
                          response = new WebResponse(data, request, response.getLoadTime());
                      }
                      return response;
                  }
              };