0

我正在使用Java在MAVEN中工作一个项目。我必须获取一个 URL,向下滚动它们,然后获取此给定网页中其他项目的所有链接。

到目前为止,我使用 Selenium 动态获取页面,并向下滚动它们,并获取链接。但这需要太多时间。请帮助我优化它。

示例:-,我正在处理一个页面,其链接在此处

我的问题:-

  1. 使用 selenium 滚动网页非常慢。我该如何优化呢?(建议任何其他方法
    来做同样的事情或帮助我优化这个)

提前致谢。寻找您的善意回应。

动态获取和滚动页面的代码:-

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import com.google.common.collect.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

/**
 *
 * @author jhamb
 */
public class Scroll_down {

    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;
    }



    public static void main(String[] args)  throws InterruptedException{
        String url1 = "http://www.jabong.com/men/shoes/men-sports-shoes/?source=home-leftnav";
        System.out.println("Fetching %s..." + url1);
        WebDriver driver = new FirefoxDriver(createFirefoxProfile());


        driver.get(url1);  

        JavascriptExecutor jse = (JavascriptExecutor)driver;
        jse.executeScript("window.scrollBy(0,250)", "");
        for (int second = 0;; second++) {
            if (second >= 60) {
                break;
            }
            jse.executeScript("window.scrollBy(0,200)", "");
            Thread.sleep(1000);
        }
            String hml = driver.getPageSource();
        driver.close();


        Document document = Jsoup.parse(hml);

            Elements links = document.select("div");

        for (Element link : links) {
            System.out.println(link.attr("data-url"));
        }
    }
}
4

2 回答 2

1

Selenium 滚动是基于 Javascript 的。不过,我不知道您使用 selenium 的目标,您没有断言可以比较代码中的任何内容吗?当您确信您的数据获取速度如此之快时,请不要使用任何睡眠方法。睡眠方法使硒变慢,但是是的,它一直在等待元素正确加载.....这取决于您,尽管要测试什么

于 2013-04-11T14:31:19.497 回答
0

下页怎么样?

ele.sendKeys(Keys.PAGE_DOWN);   //WebElement ele = <Any existing element>

重复此操作,直到找到该特定项目。

于 2014-04-04T06:34:13.517 回答