给定
<tagname class="classname">content contain "Posted by"word </tagname>
我的方法是这样的:
从网络获取所有内容。
在内容中查找“发布者”字样。
获取包含此内容的标签和类名。
我需要查找各个网站中的所有发布日期,例如 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/