groovy解析本地html文件

时间:2013-04-11 22:01:15

标签: groovy

我正在开发一个groovy脚本,它将获取所有本地html文件并解析其中的某些标记。我尝试使用像html clean之类的东西,它只是不起作用。我尝试读取每一行,但只有在我需要的东西在1行时才有效。我在github https://github.com/jrock2004/johns-octopress-scripts/blob/master/convertCompiledPosts/convertPosts.groovy上创建了这个脚本。感谢您的任何输入

编辑:所以我越来越近了。我现在有这个代码

def parser = new org.cyberneko.html.parsers.SAXParser()
new XmlParser( parser ).parse( curFile+ "/index.html" ).with { page ->
    page.'**'.DIV.grep { it.'@class'?.contains 'entry-content' }.each {
    println it
    println "--------------------------------"
    }
}

它打印的内容是

DIV[attributes={class=entry-content}; value=[P[attributes={}; value=[As an automation developer, I have learned how to write code in Java. When I am having an issue, one of the nice things that you can do is debug your code, line by line. For the longest I had wished that something like this existed in PHP. I have come to find out that you can actually debug code, like I do in Java. This is such a helpful task because I do not have to waste time using var_dump and such on variables or results. In your apache/php server you need to install and or enable something called, A[attributes={href=http://xdebug.org/}; value=[Xdebug]], . I will work on a tutorial on how to use xdebug while writing code in Sublime Text 2. So keep an eye out on my blog and or, A[attributes={href=http://www.youtube.com/jrock20041}; value=[YouTube]], channel for this tutorial.]]]]

所以基本上我想要的是我用包含类入口内容的文本包括div中的html元素。如果您想查看该页面,可以在此处找到 - http://jcwebconcepts.net/blog/2013/02/02/xdebug/

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

它确实有效...将此页面的HTML保存到文件中,然后就可以解析它了。

以下代码打印页面上每条评论的作者姓名:

@Grab('net.sourceforge.nekohtml:nekohtml:1.9.16')
def parser = new org.cyberneko.html.parsers.SAXParser()

new XmlParser( parser ).parse( file ).with { page ->
  page.'**'.A.grep { it.'@class'?.contains 'comment-user' }.each {
    println it.text()
  }
}

file设置为File指向已保存的HTML(或包含此问题的网址的String)时,会打印:

tim_yates
jrock2004
tim_yates

编辑:

要打印给定节点的内容,您可以(使用编辑过的问题中的示例):

@Grab('net.sourceforge.nekohtml:nekohtml:1.9.16')
import groovy.xml.*

def parser = new org.cyberneko.html.parsers.SAXParser()

new XmlParser( parser ).parse( 'http://jcwebconcepts.net/blog/2013/02/02/xdebug/' ).with { page ->
  page.'**'.DIV.grep { it.'@class'?.contains 'entry-content' }.each { it ->
    println XmlUtil.serialize( it )
  }
}