【发布时间】:2011-08-05 22:51:37
【问题描述】:
我有一些代码可以模拟递归树遍历,以使用 SeleniumRC 从 HTML 树中抓取内容。我已经使用 Xpath 和 CSS 定位器运行了代码。
树表示为一系列嵌套表。如果它很重要,一些树内容开始时不可见,因为分支被“折叠”了。对于 Xpath 和 CSS,树在可见和不可见方面处于相同的状态。
为了获取节点值,我的代码以“根”表达式开始,添加可以为每个连续的兄弟节点递增的“分支”标记,然后使用“节点”标记来获取文本内容。
一切正常,但使用我想出的 CSS 表达式要慢得多。
我认为这是一种制作定位器表达式的笨拙方式,尽管它适用于我的目的。我只是想弄清楚如何最好地使用 CSS 来接近使用 Xpath 所涉及的时间。
循环测试了许多无效的表达式(一直在寻找第 n 个兄弟直到找不到)并且表达式变得很长,因为我越来越深入地钻入嵌套表。
下面是来自递归的表达式和示例。如果有人能提供一些关于我正在做什么使 CSS 比 Xpath 花费更长的时间的见解,那将非常有帮助。
我完全是个新手,不擅长对 HTML 内容进行这种操作,如果您在我如何从 Xpath 迁移到 CSS 方面看到一些愚蠢的东西,请说出来。
XPath “令牌”:
final String rootbase = "//*[contains(@id,\"treeBox\")]/div";
// in next string, "{branchIncrement}" will be replaced with integer values from 2 to get to text content, and skip graphical elements
final String leveltoken = "/table/tbody/tr[{branchIncrement}]/td[2]";
final String nodetoken = "/table/tbody/tr/td[4]/span";
CSS“令牌”:
final String rootbase = "css=[id*=treeBox]>div";
// in next string, "{branchIncrement}" will be replaced with integer values from 2 to get to text content, and skip graphical elements
final String leveltoken = ">table>tbody>tr:nth-child({branchIncrement})>td:nth-child(2)";
final String nodetoken = ">table>tbody>tr>td:nth-child(4)>span";
“根”处内容的第一个 XPath 表达式是:
//*[contains(@id,"treeBox")]/div/table/tbody/tr[2]/td[2]/table/tbody/tr/td[4]/span
40 节点树的最后一个 XPath 表达式有四个级别,每个级别在根 (1+3+3x3+3x3x3) 下的三个兄弟节点是:
//*[contains(@id,"treeBox")]/div/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[3]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]/table/tbody/tr/td[4]/span
第一个 CSS 表达式是:
[id*=treeBox]>div>table>tbody>tr:nth-child(2)>td:nth-child(2)>table>tbody>tr>td:nth-child(4)>span
最后一个 CSS 表达式是:
[id*=treeBox]>div>table>tbody>tr:nth-child(2)>td:nth-child(2)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table>tbody>tr:nth-child(3)>td:nth-child(2)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table>tbody>tr>td:nth-child(4)>span
【问题讨论】:
标签: screen-scraping css-selectors selenium-rc xpath