【问题标题】:Extract HTML at XPath of HTML file在 HTML 文件的 XPath 处提取 HTML
【发布时间】:2012-12-19 22:00:39
【问题描述】:

我正在尝试从给定 Xpath 的文件中获取 html 代码。我尝试使用 HTMLUnit,但从谷歌缓存下载的这些静态文件似乎不太好。我对 HTMLCleaner 的运气要好一些,但到目前为止,我只能获得文本而没有 HTML 代码。任何的意见都将会有帮助。以下是我目前使用的代码。

TagNode tagNode = new HtmlCleaner().clean(readFile(htmlCacheFile));
Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);

XPath xpath = XPathFactory.newInstance().newXPath();
String title = ((String) xpath.evaluate(TITLE_XPATH, doc, XPathConstants.STRING)).trim();
String body =  ((String) xpath.evaluate(BODY_XPATH, doc, XPathConstants.STRING)).trim();

【问题讨论】:

    标签: java parsing html-parsing htmlunit htmlcleaner


    【解决方案1】:

    必须是 Java 解决方案吗?使用在无头浏览器中运行的站点抓取工具完全可以实现您想要做的事情。 PhantomJs 是一个无头 WebKit,它允许您在网页上执行 JavaScript/CoffeeScript。我认为它可以帮助您解决问题。

    Pjscrape 是一个基于 PhantomJs 的有用的web scraping 工具。

    这是一个示例 (config.js),它记录到控制台(也可以归档):

    pjs.addSuite({
      url: 'http://stackoverflow.com/',
      noConflict: true,
      scraper: function() {
        var html = _pjs.$('body').html();
        return html;
      }
    });
    

    phantomjs pjscrape.js config.js开头

    结果:

    * Suite 0 starting
    * Opening http://stackoverflow.com/
    * Scraping http://stackoverflow.com/
    * Suite 0 complete
    * Writing 1 items
    ["\n    <noscript>&lt;div id=\"noscript-padding\"&gt;&lt;/div&gt;</noscript>\n    <div id=\"notify-container\"></div>\n    <div id=\"overlay-header\"></div>\n    <div id=\"custom-header\"></div>\n\n    <div class=\"container\">\n        <div id=\"header\">\n            <div id=\"portalLink\">\n                <a class=\"genu\" onclick=\"StackExchange.ready(function(){genuwine.click();});return false;\">Stack Exchange</a>\n   
    
    ...
    

    【讨论】:

      【解决方案2】:

      也许这有帮助。在下面的链接中有相同问题的 XPath 示例和 JSoup 解决方案。如果你熟悉 CSS 选择器(有很多解析、清理等方法),请使用 jsoup,它是一个非常强大的 html 解析库。如果我理解目标是从文件中获取正文和标题。

      我对这个问题的解决方案是:

      Document webpage = Jsoup.parse(new File("file.html"), "UTF-8");
      System.out.println(webpage.title()+" "+webpage.body().html());
      

      https://norrisshelton.wordpress.com/2011/01/27/jsoup-java-html-parser/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-12
        • 2011-07-31
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-29
        相关资源
        最近更新 更多