gpt4 book ai didi

java - 我如何获取 html 代码内容中包含单词的标签和类名

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:06 25 4
gpt4 key购买 nike

给定

<tagname class="classname">content contain "Posted by"word </tagname>

我的方法是这样的:

  1. 从网络获取所有内容。

  2. 在内容中查找“发布者”字样。

  3. 获取包含此内容的标签和类名。

我需要查找各个网站中的所有发布日期,例如 http://www.testthisblog.com/

该网站的HTML代码中有一些内容包含“Posted by”字样。

<span class="chronodata">
Posted by
Eric Jacobson
at
<a class="timestamp-link" href="http://www.testthisblog.com/2014/05/documenting-tests-part-2-tester-leaves.html" title="permanent link">Tuesday, May 27, 2014</a>
</span>

所以我尝试使用此 Java 代码在内容中搜索“发布者”一词

String url = "http://www.testthisblog.com";

/*step1*/
Document doc = Jsoup.connect(url).get();
String htmlTxt = doc.text().toLowerCase();
Pattern pattern = Pattern.compile(".*Posted by.*");
/*step2*/
Matcher matcher = pattern.matcher(htmlTxt);
if(matcher.find()){
System.out.println("Find a word!!!");

/*step3*/ >>What is possible? can I get tag and class name here?<<
}

我使用Jsoup库,这个方法对于其他网站应该是灵活的。

最佳答案

这是可能的;一种方法是在每个元素文本上应用正则表达式,以防它匹配 get 标签和类

    String url = "http://www.testthisblog.com";

Pattern pattern = Pattern.compile(".*Posted by*");

Document doc = Jsoup.connect(url).get();
Elements els = doc.getAllElements();
for (int i = 0; i < els.size(); i++) {
Element element = els.get(i);
String txt = element.ownText();
Matcher matcher = pattern.matcher(txt);
if (matcher.find()) {
System.out.println(txt);
System.out.println(element.tagName());
System.out.println(element.className());
}
}

关于java - 我如何获取 html 代码内容中包含单词的标签和类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com