【问题标题】:jsoup getElementsByAttribute Issuejsoup getElementsByAttribute 问题
【发布时间】:2012-10-24 11:14:37
【问题描述】:

这里输入代码

<table style=”padding: 0px; margin: 0px;” cellpadding="0" cellspacing="0" width="626" align="center" bgcolor="White" border="0">
<tr>
<td style=”vertical-align: top;” height="61" valign="top" bgcolor="#0492CB"><a href="http://www.aoec.com"> <img alt="AoEC" src="http://www.aoec.com/email/mute/images/header.gif" style="width: 626px; height: 61px;" border="0" /></a></td>
</tr>
</table>

java编码是

Document doc = Jsoup.parse(code);
Elements elements = doc.getElementsByAttribute("style");
for(int se=0;se<elements.size();se++)
{
 System.out.println(elements.get(se).attr("style"));
}

输出是

padding:;
vertical-align:;

在上面的代码中 getElementsByAttribute("style") 不起作用..

【问题讨论】:

    标签: java html-parsing jsoup


    【解决方案1】:

    大括号 不是有效的属性分隔符。您需要直引号:"'

    您的代码很好。输入的 HTML 无效。这必须报告给原始 HTML 作者,以便她/他可以修复 HTML(即,它也会在普通的网络浏览器中中断)。

    如果此 HTML 超出您的控制范围,请考虑使用 String#replace() 替换无效引号。

    code = code.replace('”', '"');
    

    或者,如果您的环境中的字符编码尚未正确配置为 UTF-8。

    code = code.replace('\u201D', '"')
    

    【讨论】:

    • 我处理这种类型的引用,我尝试使用 ASCII 值删除“但有时出现问题;
    • code = code.replace('"', '"'); 在替换 ? 的网络应用中不起作用
    • 显然您的代码没有使用 UTF-8 正确保存。请改用code = code.replace('\U201D', '"')。无论如何,我强烈建议修改您的环境中使用的字符编码。顺便说一句,“ASCII 148”这个词没有意义。你有什么想法或稍微了解你在说什么以及这里发生了什么?
    • eclipse 编辑器中的转义序列无效
    • 对不起,小写u,所以code = code.replace('\u201D', '"')
    【解决方案2】:

    我认为这已经被弃用了。您应该使用.select(); 方法。此外,在循环中使用 foreach 或 iterator 是个好主意,因为简单的 for 可能会抛出一些 NullPointerExceptions

    你可以找到它的文档here

    但我不会使用它:

    //That should get you all tags that have the style attribute
    Elements elements = doc.select("[style]");
    
    //That foreach should avoid exceptions, and loop through the collection 
    for(Element element : elements) {
        //The print gets a little cleaner too!
        System.out.println(element.attr("style"));
    }
    

    【讨论】:

    • 我知道,但在这种情况下使用另一个双引号,因此会产生问题。我的问题是如何处理这个报价。
    • 如果你有一个标签 stile="something=""something=""",它会随着你使用我刚刚的目的而出现
    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2019-04-14
    • 2015-06-06
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2015-08-02
    • 2013-01-18
    相关资源
    最近更新 更多