简体   繁体   English

使用 groovy 从 html 文件打印特定行

[英]Print a specific line from html file using groovy

I am trying to print the value from HTML file and use this value in my pipeline script in Jenkins but I am unable to print this value我正在尝试打印 HTML 文件中的值,并在 Jenkins 的管道脚本中使用此值,但我无法打印此值

def test = new File('copy.html').eachLine(5) { line, number-> 
    println "$number $line"
}

copy.html复制.html

<div class="suite hidden">
  <div class="summary">
    <span class="strong">Specs</span>
    <span>Total: 2</span>
    <span>Passed: 2</span>
    <span>Failed: 0</span>
    <span>Pending: 0</span>
    <span>Disabled: 0</span>
    <span>Duration: 13.6 sec</span>
  </div>

I am trying to print the 6th line form this copy.html, ie "Failed: 0" just need this value, could someone help me here.我正在尝试从这个副本中打印第 6 行。html,即“失败:0”只需要这个值,有人可以在这里帮助我。

As this is an HTML file, it would be better to use any HTML parsing library.由于这是一个 HTML 文件,因此最好使用任何 HTML 解析库。 You almost always can use XML Parser ( http://docs.groovy-lang.org/latest/html/api/groovy/util/XmlParser.html ) for that:您几乎总是可以使用XML 解析器http://docs.groovy-lang.org/latest/html/api/groovy/util/XmlParser.ZFC35FDC70D5FC69D269E3Z 3A822C7A

def parser = new XmlParser()
// Here we parsing your file
def report = parser.parse("copy.html");
        
// And here we iterate over all the spans

println "${report.div.div.span[5].text()}"

Please look at this tutorial for more information: https://www.baeldung.com/groovy-xml请查看本教程以获取更多信息: https://www.baeldung.com/groovy-xml

Of course, XMLParser would not work if HTML you work with is not well-formed XML, but in your example it looks like should work.当然,如果您使用的 HTML 不是格式正确的 XML,则 XMLParser 将不起作用,但在您的示例中它看起来应该可以工作。

If your Jenkins job run on linux machine, you can use bash to do that如果您的 Jenkins 作业在 linux 机器上运行,您可以使用 bash 来执行此操作

def failed = sh(returnStdout: true, 
   script: '''set +x; grep Failed copy.html | sed s,/,, | awk -F '<span>' '{print $2}' ''').trim()

echo failed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM