java - Selenium 需要大量时间来获取给定 URL 的动态页面

标签 java dom selenium selenium-webdriver jsoup

我正在用 Java 做一个项目。 在这个项目中我必须使用 DOM。 为此,我首先使用 Selenium 加载任何给定 URL 的动态页面。 然后我使用 Jsoup 解析它们。

我想获取给定URL的动态页面源代码

代码快照:

public static void main(String[] args) throws IOException {

     // Selenium
     WebDriver driver = new FirefoxDriver();
     driver.get("ANY URL HERE");  
     String html_content = driver.getPageSource();
     driver.close();

     // Jsoup makes DOM here by parsing HTML content
     Document doc = Jsoup.parse(html_content);

     // OPERATIONS USING DOM TREE
}

但问题是,Selenium 占用了整个处理时间的 95% 左右,这是不希望的。

Selenium 首先打开 Firefox,然后加载给定页面,然后获取动态页面源代码。

你能告诉我如何通过用另一个高效的工具替换这个工具来减少 Selenium 所花费的时间吗?任何其他建议也将受到欢迎。

编辑编号1

link 给出了一些代码.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);

但是这里的第二行是什么,我不明白。由于文档中的 Selenium 也非常缺乏。

编辑2

System.out.println("正在获取 %s..."+ url1); System.out.println("正在获取 %s..."+ url2);

    WebDriver driver = new FirefoxDriver(createFirefoxProfile());

    driver.get("url1");  
    String hml1 = driver.getPageSource();

    driver.get("url2");
    String hml2 = driver.getPageSource();
    driver.close();

    Document doc1 = Jsoup.parse(hml1);
    Document doc2 = Jsoup.parse(hml2);

最佳答案

试试这个:

public static void main(String[] args) throws IOException {

    // Selenium
    WebDriver driver = new FirefoxDriver(createFirefoxProfile());
    driver.get("ANY URL HERE");
    String html_content = driver.getPageSource();
    driver.close();

    // Jsoup makes DOM here by parsing HTML content
    // OPERATIONS USING DOM TREE
}

private static FirefoxProfile createFirefoxProfile() {
    File profileDir = new File("/tmp/firefox-profile-dir");
    if (profileDir.exists())
        return new FirefoxProfile(profileDir);
    FirefoxProfile firefoxProfile = new FirefoxProfile();
    File dir = firefoxProfile.layoutOnDisk();
    try {
        profileDir.mkdirs();
        FileUtils.copyDirectory(dir, profileDir);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return firefoxProfile;
}

如果配置文件不存在,createFireFoxProfile() 方法会创建一个配置文件。如果配置文件已存在,则使用它。所以selenium不需要每次都创建profile-dir结构。

关于java - Selenium 需要大量时间来获取给定 URL 的动态页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15830334/

相关文章:

java - Guava 函数根据对列表中每个项目的应用条件将项目添加到结果集合中

python - 如果出现几秒钟,如何从 <span class> 的 python 中获取带有 Selenium 的文本?

java - 带有 fragment 和 Activity 的 FragmentActivity TabHost

java - CharBuffer 与 char[]

java逆变疑问

Javascript 在 DOM 中查找给定 div 及其内容的出现

javascript - 如何在 DOM 上触发 js 创建的触摸事件

javascript - c.replace 不是一个函数

python - 使用 Python/Selenium 从 Angular 网站中选择复选框

java - Selenium 脚本测试运行的 RateLimit 问题