【问题标题】:How to extract the content attribute of the meta name=generator tag?如何提取 meta name=generator 标签的内容属性?
【发布时间】:2012-01-07 22:51:00
【问题描述】:

我正在使用以下代码使用 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”显示正确。我在这里做错了什么?

【问题讨论】:

    标签: java html-parsing jsoup


    【解决方案1】:

    根据您的代码,

    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 块内的 boolean 进行测试。 isEmpty()已经返回boolean

    if (!metalinks.isEmpty())
    

    【讨论】:

    • 不客气。对于未来的选择器问题,请阅读“另见”链接。它包含许多有价值的例子。
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2014-06-14
    • 2015-09-02
    • 2020-04-09
    相关资源
    最近更新 更多