提问者:小点点

加速硒网络驱动?


我正在使用selenium网络驱动程序来自动使用网页。不允许使用无头浏览器。

Selenium在完全加载的单个页面上查找多个元素似乎相当缓慢。

有人对如何加快速度有什么建议吗?我通常通过xpath搜索对象。

我已经搜索了谷歌和阅读类似的SO帖子。我正在寻找新的想法


共2个答案

匿名用户

在这种情况下,我喜欢创建一个org。w3c。dom文档使用页面源,然后使用javax. xml库对其进行解析:

public static Document getWebpageDocument_fromSource(String source) throws InterruptedException, IOException {
    try {
        HtmlCleaner cleaner = new HtmlCleaner();
        CleanerProperties props = cleaner.getProperties();
        props.setAllowHtmlInsideAttributes(true);
        props.setAllowMultiWordAttributes(true);
        props.setRecognizeUnicodeChars(true);
        props.setOmitComments(true);

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        TagNode tagNode = new HtmlCleaner().clean(source);

        Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);

        return doc;
    } catch (ParserConfigurationException ex) {
        ex.printStackTrace();
        return null;
    }
}

然后通过xpath访问元素,如下所示:

String myXpathStr = "//*[@id='news-main']/div";
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList articleBlocks = (NodeList)xPath.compile(myXpathStr).evaluate(doc, XPathConstants.NODESET);

希望有帮助。我也同意id和css更快的其他答案。我发现xpath更强大,但我对css路径没有太多经验

匿名用户

我通过id类名和其他容易识别的元素进行搜索。但是速度将基于网络连接和硬件等因素。你总是可以使用HTMLDriver,因为这将是驱动程序的最快版本。