您如何使用Java中的Selenium获取页面的常规(!)源代码?

时间:2018-08-19 17:38:04

标签: java selenium

好吧,这就是问题:所有人可能都在思考同一件事:可以使用

driver.getPageSource();

这是部分正确的。唯一的问题是,以一种相当奇怪的方式对源代码进行了编译,其中整个代码

\"

开始显示。我尝试手动删除它,但仍然不能完全解决问题。

我的意思的一个例子:

正常源代码:

\"query_title\":null}",encoded_title:"WyJoZW5rIl0",ref:"unknown",logger_source:"www_main",typeahead_sid:"",tl_log:false,impression_id:"bbdb1882",filter_ids:

硒输出:

\\\"query_title\\\":null}\",\"encoded_title\":\"WyJoZW5rIl0\",\"ref\":\"br_tf\",\"logger_source\":\"www_main\",\"typeahead_sid\":\"0.6583900225217523\",\"tl_log\":false,\"impression_id\":\"e00060b4\",\"filter_ids\"

这似乎与您必须在引号中的某些符号前面放置某些内容,以防止Java将其视为其中一种符号一样,但是我不完全理解这种行为,并且不知道如何解决...希望您能提供帮助:)

编辑: 由于编译的方式,替换不起作用。我先前提供的示例实际上是一个为什么它不起作用的示例:

原始:

}",encoded_title:

编译版本:

}\",\"encoded_title\":

用\替换\“会将其更改为:

}","encoded_title":

与原始版本不同...

如果我不使用任何内容替换\“,我将得到:

},encoded_title:
遗憾的是,

仍然与原始版本有所不同。这种编译方式我不认为替换是可行的选择...

2 个答案:

答案 0 :(得分:2)

您可以使用JavaScript使用externalHTML或innerHTML(How do I get the HTML source from the page?)来获取html:

((JavascriptExecutor) driver).executeScript("return document.documentElement.outerHTML;")
((JavascriptExecutor) driver).executeScript("return document.documentElement.outerHTML;")
((JavascriptExecutor) driver).executeScript("return document.all[0].outerHTML")
((JavascriptExecutor) driver).executeScript("return new XMLSerializer().serializeToString(document);")

答案 1 :(得分:0)

您可以使用Java字符串类 replaceAll 方法将不需要的字符替换为所需的字符。

旧解决方案-

 driver.getPageSource().replaceAll("\\"", "\"").replaceAll("\\\\", ""));

新的近似解决方案-页面源可以包含HTML中的任何内容

public class CheckString {


    static String str = "\\\\\\"query_title\\\\\\":null}\\",\\"encoded_title\\":\\"WyJoZW5rIl0\\",\\"ref\\":\\"br_tf\\",\\"logger_source\\":\\"www_main\\",\\"typeahead_sid\\":\\"0.6583900225217523\\",\\"tl_log\\":false,\\"impression_id\\":\\"e00060b4\\",\\"filter_ids\\"";

    public static void main(String[] args) {

    System.out.println(str.replaceAll("\\\\",","\",")
                          .replaceAll(":\\\\"", ":\"")
                          .replaceAll("\\\\"","")
                          .replaceAll("\\\\\\\\", "\\\\\""));

    }

}

输出-

  
    

\“ query_title \”:null}“,已编码标题:” WyJoZW5rIl0“,ref:” br_tf“,logger_source:” www_main“,typeahead_sid:” 0.6583900225217523“,tl_log:false,impression_id:” e00060b4“,filter_ids   

注意-在较早的方法中,我忘记了转义&字符,而replaceAll函数将其用于分隔正则表达式中的多个条件