Java Selenium:如何在不先加载页面的情况下获取网页的 HTML? [英] Java Selenium: how can I get the HTML of a webpage without first loading the page?

查看:33
本文介绍了Java Selenium:如何在不先加载页面的情况下获取网页的 HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Selenium WebDriver for Java,是否可以在给定 URL 的情况下获取网页的 HTML?

Using Selenium WebDriver for Java, is it possible to get the HTML of a webpage given a specified URL?

我知道,在浏览器中加载网页后,可以使用 WebDriver.getPageSource() 获取 HTML.但是,为了提高效率,是否可以在不先在浏览器中加载页面的情况下获取 HTML?

I know that, once a webpage is loaded in a browser, the HTML can be obtained using WebDriver.getPageSource(). However, for improved efficiency, is it possible to obtain the HTML without loading the page in a browser first?

推荐答案

您可以使用 无头浏览器.

无头浏览器是一种没有图形用户界面的网络浏览器.该程序的行为就像浏览器一样,但不会显示任何 GUI.

无头浏览器通常用于以下情况:-

Headless browsers are typically used in following situations :-

  • 您有一个没有安装任何浏览器的中央构建工具.因此,要在每次构建后进行基本级别的健全性测试,您可以使用无头浏览器来运行测试.

  • You have a central build tool which does not have any browser installed on it. So to do the basic level of sanity tests after every build you may use the headless browser to run your tests.

如果你想编写一个爬虫程序,遍历不同的页面并收集数据,无头浏览器将是你的选择.因为你真的不在乎打开浏览器.您只需访问网页即可.

You want to write a crawler program that goes through different pages and collects data, headless browser will be your choice. Because you really don’t care about opening a browser. All you need is to access the webpages.

您想在同一台机器上模拟多个浏览器版本.在这种情况下,您会想要使用无头浏览器,因为它们中的大多数都支持模拟不同版本的浏览器.我们很快就会谈到这一点.

You would like to simulate multiple browser versions on the same machine. In that case you would want to use a headless browser, because most of them support simulation of different versions of browsers. We will come to this point soon.

使用无头浏览器前的注意事项

无头浏览器是模拟程序,它们不是你真正的浏览器.这些无头浏览器中的大多数已经发展到足以模拟到非常接近的近似值,就像真正的浏览器一样.您仍然不想在无头浏览器中运行所有测试.JavaScript 是您在使用 Headless 浏览器之前需要非常小心的一个领域.不同的浏览器以不同的方式实现 JavaScript.虽然 JavaScript 是一个标准,但每个浏览器在实现 JavaScript 的方式上都有自己的细微差别.在无头浏览器的情况下也是如此.例如 HtmlUnit 无头浏览器使用 Rihno JavaScript 引擎,其他浏览器都没有使用.

Headless Drivers 的一些示例包括

Some of the examples of Headless Drivers include

  • HtmlUnit
  • 幽灵
  • PhantomJS
  • 僵尸JS
  • Watir-webdriver

这篇关于Java Selenium:如何在不先加载页面的情况下获取网页的 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆