如何使用xpath迭代匹配css类的DOM元素?

GJ.*_*GJ. 9 html css xpath selenium-rc

我正在使用Python + Selenium RC处理带有可变数量的p元素的HTML页面,其中css类为"myclass".

当我尝试使用此xpath选择每个节点时:

//p[@class='myclass'][n]
Run Code Online (Sandbox Code Playgroud)

(用na自然数)

对于每个n,我只得到第一个带有此css类的p元素,这与我通过选择所有p元素迭代的情况不同:

//p[n]
Run Code Online (Sandbox Code Playgroud)

有没有办法可以使用xpath通过css类迭代元素?

Dim*_*hev 2

XPath 1.0 不提供迭代构造

可以使用托管 XPath 的语言对选定的节点集执行迭代。

例子

在 XSLT 1.0 中

   <xsl:for-each select="someExpressionSelectingNodes">
     <!-- Do something with the current node -->
   </xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

在 C# 中

using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.Load("booksort.xml");

    XmlNodeList nodeList;
    XmlNode root = doc.DocumentElement;

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']");

    //Change the price on the books.
    foreach (XmlNode book in nodeList)
    {
      book.LastChild.InnerText="15.95";
    }

    Console.WriteLine("Display the modified XML document....");
    doc.Save(Console.Out);

  }
}
Run Code Online (Sandbox Code Playgroud)

XPath 2.0 有自己的迭代结构

   for $varname1 in someExpression1,
       $varname2 in someExpression2, 
      .  .  .  .  .  .  .  .  .  .  .
       $varnameN in someExpressionN 
    return
        SomeExpressionUsingTheVarsAbove
Run Code Online (Sandbox Code Playgroud)