2015-11-28 99 views
1

对于以下HTML:Jsoup选择语法工作不正常

<table> 
<tbody> 
    <tr valign="TOP"> 
    <td align="LEFT"><b>Licensee Name:</b></td> 
    <td align="LEFT">Some-last-name Some-first-name</td> 
    </tr> 
    <tr valign="TOP"> 
    <td align="LEFT"><b>License Type:</b></td> 
    <td align="LEFT">Optometrist (OPT)</td> 
    </tr> 
. 
. 
. 
</tbody> 
</table> 

下面的代码生成元素的空集:

Elements rows = docOptometristDetail.select("body > table ~ tr"); 

但此代码的工作:

tables = docOptometristDetail.select("body > table"); 
Elements rows = tables.select("tr"); 

我期待波代码操作符:

table ~ tr 

找到<table>元素,跳过<tbody>元素并构建<tr>元素的集合。

我在Jsoup的选择器语法分析器中发现了一个弱点,还是我试图违反一些运算符优先规则?我试过(body > table) ~ tr但是抛出了SelectorParseException

有没有办法用单个选择器表达式来做这个选择(即得到一个Elements元素的集合)?

回答

1

在CSS中,波浪号字符~general sibling combinator

选择器table ~ tr将试图选择继table元件所述的tr同级元素。由于table元素和tr元素不能是兄弟,因此不会选择任何内容。

从理论上讲,选择table ~ tr会选择以下tr元素:

<table></table> 
<tr></tr> <!-- These 'tr' elements are following siblings of the 'table' --> 
<tr></tr> <!-- This is invalid HTML, though. --> 

这听起来像你只需要选择后代,因此body > table tr会工作。

+0

这是行不通的!谢谢。如果桌子在体内,你可以通过“body> table”进入桌子。因此,如果行在表格内,为什么不使用“table> tr”(我曾尝试过,没有成功)? – mbmast

+0

@mbmast这是因为'>'会选择* direct *子元素,而一个空格会选择所有的子元素。 'tr'元素不是'table'元素的直接子元素,但是它们是子元素。参见:http://stackoverflow.com/questions/3225891/what-does-the-greater-than-sign-css-selector-mean –