java – Selenium – driver.getPageSource()与从浏览器中查看的源不同

前端之家收集整理的这篇文章主要介绍了java – Selenium – driver.getPageSource()与从浏览器中查看的源不同前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用selenium从指定的 HTML文件中捕获源代码,但我不知道为什么,我没有得到我们从浏览器中看到的确切源代码.

下面是我在Java文件中捕获源代码的java代码

  1. private static void getHTMLSourceFromURL(String url,String fileName) {
  2.  
  3. WebDriver driver = new FirefoxDriver();
  4. driver.get(url);
  5.  
  6. try {
  7. Thread.sleep(5000); //the page gets loaded completely
  8.  
  9. List<String> pageSource = new ArrayList<String>(Arrays.asList(driver.getPageSource().split("\n")));
  10.  
  11. writeTextToFile(pageSource,originalFile);
  12.  
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16.  
  17. System.out.println("quitting webdriver");
  18. driver.quit();
  19. }
  20.  
  21. /**
  22. * creates file with fileName and writes the content
  23. *
  24. * @param content
  25. * @param fileName
  26. */
  27. private static void writeTextToFile(List<String> content,String fileName) {
  28. PrintWriter pw = null;
  29. String outputFolder = ".";
  30. File output = null;
  31. try {
  32. File dir = new File(outputFolder + '/' + "HTML Sources");
  33. if (!dir.exists()) {
  34. boolean success = dir.mkdirs();
  35. if (success == false) {
  36. try {
  37. throw new Exception(dir + " could not be created");
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43.  
  44. output = new File(dir + "/" + fileName);
  45. if (!output.exists()) {
  46. try {
  47. output.createNewFile();
  48. } catch (IOException ioe) {
  49. ioe.printStackTrace();
  50. }
  51. }
  52. pw = new PrintWriter(new FileWriter(output,true));
  53. for (String line : content) {
  54. pw.print(line);
  55. pw.print("\n");
  56. }
  57. } catch (IOException ioe) {
  58. ioe.printStackTrace();
  59. } finally {
  60. pw.close();
  61. }
  62.  
  63. }

有人可以为此解释为什么会发生这种情况吗? WebDriver如何呈现页面?浏览器如何显示代码

解决方法

有几个地方你可以从中获取来源.你可以试试
  1. String pageSource=driver.findElement(By.tagName("body")).getText();

看看会出现什么.

通常,您不需要等待页面加载.Selenium会自动执行此操作,除非您有单独的Javascript / Ajax部分.

您可能想要添加您所看到的差异,以便我们了解您的真正含义.

Webdriver不会自己呈现页面,它只是在浏览器看到它时呈现它.

猜你在找的Java相关文章