我正在使用以下代码使用 Jsoup 从网页中提取元“生成器”标记内容:
Elements metalinks = doc.select("meta[name=generator]");
boolean metafound=false;
if(metalinks.isEmpty()==false)
{
metatagcontent = metalinks.first().select("content").toString();
metarequired=metatagcontent;
metafound=true;
}
else
{
metarequired="NOT_FOUND";
metafound=false;
}
问题是对于包含元生成器标签的页面,没有显示任何值(当我输出变量“metarequired”的值时。对于没有元生成器标签的页面,值“NOT_FOUND”显示正确。我在这里做错了什么?
最佳答案
从您的代码,
metalinks.first().select("content").toString();
这是不正确的。这只是选择
<meta ...>
<content ... /> <!-- This one, which of course doesn't exist. -->
</meta>
当您实际上想要获取属性时
<meta ... content="..." />
您需要使用 attr("content")
而不是 select("content")
.
metatagcontent = metalinks.first().attr("content");
另见:
与具体问题无关,您不需要针对 if
block 内的 boolean
进行测试。 isEmpty()
已经 返回一个 boolean 值
:
if (!metalinks.isEmpty())
关于java - 如何提取meta name=generator标签的content属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8296520/