compiler-errors - 如何使Groovy Shell读取#符号

我无法让以下代码在Groovy中进行编译。

String execute(Document doc){

    CompilerConfiguration configuration = new CompilerConfiguration()
    configuration.setSourceEncoding("UTF-8")

    binding = new Binding();
    binding.setVariable("doc", doc)

    shell = new GroovyShell(binding, configuration)

    String clipping = shell.evaluate("doc."+jsoupExpression+".text()")

    return clipping

}

当我这样调用我的函数时,应该执行以下命令:
//Use a document from test/resources as input
Document doc = Jsoup.parse(new File("test/resources/online.html"), "UTF-8")

//This is what gets passed as jsoupExpression
Rule r = new Rule("select(div#unten div h2).get(1)")

String result = r.execute(doc)

我得到的是这个异常(exception):
| Failure:  testExecute(com.threefact.scrapetastic.RuleTests)
|  org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected char: '#' @ line 1, column 15.
   doc.select(div#unten div h2).get(1).text()
                 ^
1 error

我用谷歌搜索了一段时间,但无法提出解决方案。也许有人已经经历过类似的情况,可以帮助我解决这个问题。

谢谢。

最佳答案

问题是这一行:

Rule r = new Rule("select(div#unten div h2).get(1)")

隔离规则后,您将获得以下程序:
select(div#unten div h2).get(1)

我认为您想将字符串参数传递给select,所以这将是正确的程序:
select("div#unten div h2").get(1)

这意味着Rule r行应编写如下:
Rule r = new Rule("select(\"div#unten div h2\").get(1)")

https://stackoverflow.com/questions/13659563/

相关文章:

compiler-errors - 带有C++/CLI的VS2012中的错误C2039错误

android - BadTokenException无法添加窗口(ProgressDialog)

xcode - Xcode无法识别C++语法

gcc - 如何在 MinGW 中将错误消息控制设置为详细?

python - scipy给出了 undefined symbol : clapack_sgesv

compiler-errors - 免费的基本编译器错误23 : File not found, l

c# - 编译委托(delegate)和调度程序时出错

Objective-C - 避免编译错误?

wpf - WPF,将XAML文件移动到另一个项目

git - 移动git项目导致许多Blob和树错误