xpath 在 java 中不工作

发布于 2024-07-29 09:07:29 字数 845 浏览 5 评论 0原文

我正在尝试访问一个 url,从中获取 html 并使用 xpaths 从中获取某些值。 我得到的 html 很好,Jtidy 似乎正在适当地清理它。 但是,当我尝试使用 xpath 获取所需的值时,我得到一个空的 NodeList。 我知道我的 xpath 表达式是正确的; 我已经通过其他方式进行了测试。 这段代码有什么问题。 谢谢您的帮助。

String url_string = base_url + countries[c];
URL url = new URL(url_string);

Tidy tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setXHTML(true);
tidy.setMakeClean(true);
Document doc = tidy.parseDOM(url.openStream(), null);
//tidy.pprint(doc, System.out);

String xpath_string = "id('catlisting')//a";
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpath_string);

NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("size="+nodes.getLength());
for (int r=0; r<nodes.getLength(); r++) {
    System.out.println(nodes.item(r).getNodeValue()); 
}

I am trying to access a url, get the html from it and use xpaths to get certain values from it. I am getting the html just fine and Jtidy seems to be cleaning it appropriately. However, when I try to get the desired values using xpaths, I get an empty NodeList back. I know my xpath expression is correct; I have tested it in other ways. Whats wrong with this code. Thanks for the help.

String url_string = base_url + countries[c];
URL url = new URL(url_string);

Tidy tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setXHTML(true);
tidy.setMakeClean(true);
Document doc = tidy.parseDOM(url.openStream(), null);
//tidy.pprint(doc, System.out);

String xpath_string = "id('catlisting')//a";
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpath_string);

NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("size="+nodes.getLength());
for (int r=0; r<nodes.getLength(); r++) {
    System.out.println(nodes.item(r).getNodeValue()); 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蒲公英的约定 2024-08-05 09:07:35

尝试“//div[@id='catlisting']//a”

Try "//div[@id='catlisting']//a"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文