发布新日志

  • selenium+xpath应用技巧-单引号双引号处理篇

    2009-04-09 09:35:54

     

    当xpath中的内容只含有单引号或只含有双引号时,处理都是比较简单的

    例:
    只含有单引号的处理:
    title内容为:a'a
    slenium.isElementPresent("//tr/td[@title=\"a'a\"]");

    只含有双引号的处理:
    title内容为:a"a
    slenium.isElementPresent("//tr/td[@title='a\"a']");

    即用单引号包含双引号,双引号包含单引号,另外如果有多层时,注意使用\"的方式转义;

     

    如果内容同时包含单引号及双引号时,处理的方式同只有单引号或只有双引号相似;
    但注意使用xpath中的函数concat进行连接;

    例:
    title内容为:'"(即一个单引号,一个双引号)
    slenium.isElementPresent("//tr/td[@title=concat(\"'\",'\"')]");
    重点是:concat(\"'\",'\"'),因为外层还有一个双引号嵌套,所以concat中的双引号要使用\"
           简单看为:concat(" ' ",' " ')……这样看应该比较容易理解点:)

    当属性内容比较多时
    例:
    title内容为:aa'aa"aa
    slenium.isElementPresent("//tr/td[@title=concat(\"aa'\",'aa\"aa')]");
    也可以用:
    slenium.isElementPresent("//tr/td[@title=concat('aa',\"'\",'aa','\"','aa')]");
    灵活应用哦。。。

     

    http://hi.baidu.com/ligq/blog/item/9195d03f6c0200c57d1e71df.html
    这篇文章中有一个函数对xpath中的单引号、双引号进行处理

     static String QueryStringFilter(String queryStr)
        {
            queryStr = queryStr.replace("\"", "[\"]");
            queryStr = queryStr.replace("'", "',\"'\",'");
            queryStr = queryStr.replace("[\"]", "','\"','");
            queryStr = "concat('" + queryStr + "')";
            return queryStr;
        }

    之前使用replaceAll,未使用replace,所以替换后的结果不正确;
    因为replaceAll函数的第一个参数是正则表达式,即中括号会被当成正则中的特殊字符处理(解决该方法,可用"\\["代替"[",中括号的后一半"]"没有影响)

    当然也可以用别的特殊符号代替中括号,中括号主要起到分隔符的作用;

     

    另:曾尝试使用"代替双引号,'代替单引号,虽然xpath不会报语法错误,但并不能找到相匹配的element,似乎xpath不能对"及'等进行转义;
    concat()是目前找到的唯一能处理单引号、双引号同时存在的方法;
    如果有其它更好的办法,麻烦各位告知哦。。。

  • selenium+xpath应用技巧-查看源代码篇

    2009-04-08 09:23:53

    使用xpath,我们通常是右键查看源代码,再按HTML标签的嵌套关系写XPATH

    但有时会发现如下问题:

    1)XPATH怎么写都是错的
    2)多一个HTML标签就出错,少一个HTML标签就正确

    但通过firebug查看源代码写的xpath就很少有这样的问题

    这是因为,右键查看源代码,只能看到一些静态的HTML文件内容,如果HTML标签是动态生成的,右键查看源代码就显示不出来,但firebug却可以

    所以,最好使用firebug来查看源代码,但如果不习惯,也可以先通过右键查看源代码,发现问题了,再用firebug来确认下。

     

  • selenium+xpath应用技巧-日期控件My97DatePicker篇

    2009-04-07 14:55:44

    selenium自动化测试WEB
    当页面上使用了My97DatePicker日期控件时,可使用如下方法解决:

      selenium.selectFrame("relative=up");
      //点击日期文本框
      selenium.click("days");
      //必须增加Thread.sleep(),不增加会报错,提示找不到下一条命令中的元素
      //另,尝试使用waitForPageToLoad代替,会超时出错;
      Thread.sleep(5000);
      //当前为4月,向前移两个月
      selenium.click("//div[@id='dpTitle']/div[2]");
      selenium.click("//div[@id='dpTitle']/div[2]");
      //点击2009-02-02
      selenium.click("//td[@onclick='day_Click(2009,2,2);']");

     

  • selenium+xpath应用技巧-getAttribute篇

    2009-04-07 14:07:46

    selenium+xpath应用技巧-getAttribute篇

    <tr>
     <td title="aaa" >
      <span class="limit1" >aaa</span>
     </td>
    </tr>

    想获取td的title属性值,可通过:
    selenium.getAttribute("//tr/td[span]@title");

    如果想获取span的class的属性值,可通过:
    selenium.getAttribute("//tr/td/span@class");

  • 如何使selenium支持FCK Editor

    2009-04-03 14:17:04

    When u want to auto write value to FCK Editor in Selenium IDE, add a new commad like this:

     

    Command:  runScript

    Target:   FCKeditorAPI.GetInstance("Your_FCK_Editor_ID_In_HTML_source_code").SetHTML("What_you_want_to_input");

     

    Ignore the Value property.

     

    The testing script. source is :

    ......

    <tr>
        <td>runScript</td>
        <td>FCKeditorAPI.GetInstance("fck_contact_information").SetHTML("Shanghai,China")</td>
        <td></td>
    </tr>

    <tr>
        <td>pause</td>
        <td>20000</td>
        <td></td>
    </tr>

    ......

     

    转换为JAVA代码如下:

     

    selenium.runScript("FCKeditorAPI.GetInstance('unw_content').SetHTML('Shanghai,China')");

  • Xpath教程-zt

    2009-03-31 16:23:23

     

    转自:http://www.cnblogs.com/caoxch/archive/2006/11/17/563804.html

    http://www.w3school.com.cn/xpath/xpath_syntax.asp

    XPath教程

    XPath是用于在XML文件上寻找信息的一种语言。
    XPath用于操纵XML文件上的元素和属性。
    W3C的XSLT标准中XQuery和XPointer都是在XPath表达式的基础上建立起来的
    因此学习有关XPath对于提高XML的使用技巧是很有帮助的

    XPath 参考

    可以找到内置于 XPath 2.0, XQuery 1.0 和XSLT 2.0的完整函数参考

    XPath 函数

    内容目录

    XPath 介绍
    This chapter explains what XPath is.
    关于XPath的概念

    XPath 点
    This chapter defines the different types of nodes in XPath and the relationship of nodes.
    在XPath不同类型的点,以及点与点的联系

    XPath 语法
    This chapter explains the XPath syntax.
    有关XPath的语法介绍

    XPath Axes
    This chapter explains the XPath axes.
    这章介绍了XPath轴

    XPath Operators
    This chapter lists the operators that can be used in XPath expressions.
    列举了可以用在XPath中的操作符

    XPath 实例
    This chapter uses the "books.xml" document to demonstrate some XPath examples.
    使用了"books.xml"文档来演示一些XPath例子

    XPath 摘要
    This chapter contains a summary on what you have learned in this tutorial and a recommendation on what subject you should study next.
    回顾了所学的内容,并推荐下一步应该学习的内容。

    XPath介绍
    w3pop.com / 2006-09-19

    XPath Nodes(节点)

    XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document.
    XPath是用于在XML文件上寻找信息的一种语言。XPath用于操纵XML文件上的元素和属性。


    What You Should Already Know
    写在前面

    Before you continue you should have a basic understanding of the following:
    首先你要了解以下几个概念:

    • HTML / XHTML
    • XML / XML Namespaces
    • XML / XML命名空间

    If you want to study these subjects first, find the tutorials on our Home page.
    你可以从我们的首页获取相关的教程


    What is XPath?
    什么是可扩展路径(XPath)?

    • XPath is a syntax for defining parts of an XML document
    • XPath 是XML中的一种语法
    • XPath uses path expressions to navigate in XML documents
    • XPath 是XML文档中的路径索引
    • XPath contains a library of standard functions
    • XPath 包含一个标准函数库
    • XPath is a major element in XSLT
    • XPath 是一个XSLT的主要元素
    • XPath is a W3C Standard
    • XPath 是W3C标准

    XPath Path Expressions
    XPath 路径表达式

    XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system.
    XPath路径表达式用于从XML文档中选取节点或节点设置。这些语句类似于传统操作系统的语句。


    XPath Standard Functions
    XPath 标准函数

    XPath includes over 100 built-in functions. There are functions for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more.
    XPath包含100多种内置函数。包括:字符值,数字值,日期和时间方法,节点操作,排序操作,布尔值等。


    XPath is Used in XSLT
    XPath用于XSLT

    XPath is a major element in the XSLT standard. Without XPath knowledge you will not be able to create XSLT documents.
    XPath是XSLT标准的一个重要元素。在创建XSLT文档前你必须先了解XPath。

    You can read more about XSLT in our XSLT tutorial.
    你可以从我们的XSLT教程中了解更多。

    XQuery and XPointer are both built on XPath expressions. XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators.
    XQuery 和 XPointer都是基于XPath表达式构建的。它们有着相同的数据模式并支持相同的函数和操作。

    You can read more about XQuery in our XQuery tutorial.
    你可以从我们的XQuery教程中了解更多。


    XPath is a W3C Standard
    XPath 是W3C标准

    XPath became a W3C Recommendation 16. November 1999.
    XPath 在1999年11月16日成为W3C标准。

    XPath was designed to be used by XSLT, XPointer and other XML parsing software.

    You can read more about the XPath standard in our W3C tutorial.
    你可以从我们的W3C教程中了解更多。

    XPath Nodes(节点)
    w3pop.com / 2006-09-21

    XPath介绍 XPath 语法

    In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document (root) nodes.
    在XPath里,有7中不同的节点:元素,属性,文本,名称空间,处理指令,内容,文档(根目录root)节点。


    XPath Terminology
    XPath术语

    Nodes
    节点

    In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document (root) nodes. XML documents are treated as trees of nodes. The root of the tree is called the document node (or root node).
    在XPath里,有7中不同的节点:元素,属性,文本,名称空间,处理指令,内容,文档(根)节点,XML文档是节点树状结构。“树根”称作文档节点(或根节点)。

    Look at the following XML document:
    下面给出一个XML文档:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>
    <title lang="en">Harry Potter</title>

    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
    </book>
    </bookstore>

    Example of nodes in the XML document above:
    上述XML文档中的节点实例:

    <bookstore>  (document node)
    <author>J K. Rowling</author>  (element node)
    lang="en"  (attribute node)

    Atomic values
    “单元素(Atomic)”属性值

    Atomic values are nodes with no children or parent.
    “单元素”属性值只没有子节点和父节点。

    Example of atomic values:
    “单元素(Atomic)”属性值例子:

    J K. Rowling
    "en"

    Items
    项目

    Items are atomic values or nodes.
    项目是指单元素或节点。


    Relationship of Nodes
    节点间的关系

    Parent
    父类

    Each element and attribute has one parent.
    每个元素和属性都有一个“父类”。

    In the following example; the book element is the parent of the title, author, year, and price:
    在下面的例子里:book元素是title, author, year, 和 price元素的父元素。

    <book>
    <title>Harry Potter</title>
    <author>J K. Rowling</author>

    <year>2005</year>
    <price>29.99</price>
    </book>

    Children
    子类

    Element nodes may have zero, one or more children.
    节点元素可拥有任意个数的子类。

    In the following example; the title, author, year, and price elements are all children of the book element:
    在下面例子里,title, author, year, 和 price元素都是book元素的子元素。

    <book>
    <title>Harry Potter</title>

    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
    </book>

    Siblings
    同属类

    Nodes that have the same parent.
    拥有相同的父类的节点称之为同属类。

    In the following example; the title, author, year, and price elements are all siblings:
    在下面的例子里title, author, year, 和price元素都是“同属类元素”。

    <book>
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>

    <price>29.99</price>
    </book>

    Ancestors
    祖类

    A node's parent, parent's parent, etc.
    一个节点的父类,父类的父类及更多称为该节点的祖类。

    In the following example; the ancestors of the title element are the book element and the bookstore element:
    在下面例子里,title元素的“祖类元素”是book元素和bookstore元素。

    <bookstore>
    <book>
    <title>Harry Potter</title>

    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
    </book>
    </bookstore>

    Descendants
    下属类

    A node's children, children's children, etc.
    节点的子类,子类的子类及更多称为下属类。

    In the following example; descendants of the bookstore element are the book, title, author, year, and price elements:
    在下面的例子里,bookstore元素的下属类元素是book, title, author, year, 和price元素:

    <bookstore>
    <book>
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>

    <price>29.99</price>
    </book>
    </bookstore>

    XPath 语法
    w3pop.com / 2006-09-21

    XPath Nodes(节点) XPath Axes

    XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.
    XPath 通过路径表达式从XML文档中选取节点或节点设置。可以通过一条语句或相应的步骤选取一个节点。


    The XML Example Document
    XML文档实例

    We will use the following XML document in the examples below.
    我们将在接下来的文章中引用这个XML文档。

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>
    <title lang="eng">Harry Potter</title>
    <price>29.99</price>
    </book>
    <book>
    <title lang="eng">Learning XML</title>
    <price>39.95</price>
    </book>
    </bookstore>



    Selecting Nodes
    选取节点

    XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below:
    XPath通过路径表达式在XML文档中选取节点。可以通过一条语句或相应的步骤选取一个节点。下面列出了最常使用的路径表达式:

    Expression
    表达式
    Description
    注释
    nodename Selects all child nodes of the node
    选取节点下的所有子节点
    / Selects from the root node
    选取根节点
    // Selects nodes in the document from the current node that match the selection no matter where they are
    选取文档中所有符合条件的节点,不管该节点位于何处
    . Selects the current node
    选取单前节点
    .. Selects the parent of the current node
    选取单前节点的父节点
    @ Selects attributes
    选取属性

    Examples
    实例

    In the table below we have listed some path expressions and the result of the expressions:
    在下面的表格中,我们列出了一些路径表达式及其运行的结果:

    Path Expression
    表达式
    Result
    结果
    bookstore Selects all the child nodes of the bookstore element
    选取bookstore元素的所有子节点
    /bookstore Selects the root element bookstore
    选取bookstore元素的根节点

    Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!
    注意:如果一个路径以(/)开始,那么它必须是表述该元素所在的绝对路径

    bookstore/book Selects all book elements that are children of bookstore
    选取bookstore中的所有book子元素
    //book Selects all book elements no matter where they are in the document
    选取文档中的所有book元素
    bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element
    选取文档中所有处于bookstore节点下的book元素
    //@lang Selects all attributes that are named lang
    选取所有lang属性


    Predicates
    条件

    Predicates are used to find a specific node or a node that contains a specific value.
    它指定了选取节点的范围。

    Predicates are always embedded in square brackets.
    通常使用方括号[ ]来指定条件。

    Examples
    实例

    In the table below we have listed some path expressions with predicates and the result of the expressions:
    在下面的表格中我们列出了一些指定条件的表达式及其运行结果:

    Path Expression
    表达式
    Result
    结果
    /bookstore/book[1] Selects the first book element that is the child of the bookstore element
    选取bookstore节点下的第一个book元素
    /bookstore/book[last()] Selects the last book element that is the child of the bookstore element
    选取bookstore节点下的最后一个book元素
    /bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
    选取bookstore节点下的倒数第二个book元素
    /bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element
    选取bookstore节点下的前两个book元素
    //title[@lang] Selects all the title elements that have an attribute named lang
    选取所有包含有lang属性的title元素
    //title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng'
    选取所有lang属性值为‘eng’的title元素
    /bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00
    选取bookstore节点下的所有包含price元素大于35.00的book元素
    /bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00
    选取bookstore节点下的所有包含price元素大于35.00的book节点下的title元素


    Selecting Unknown Nodes
    选取未知节点

    XPath wildcards can be used to select unknown XML elements.
    可以通过 XPath 通配符选取未知的XML元素。

    Wildcard
    通配符
    Description
    注释
    * Matches any element node
    匹配任意的节点元素
    @* Matches any attribute node
    匹配任意的节点属性
    node() Matches any node of any kind
    匹配任意种类的节点

    Examples
    实例

    In the table below we have listed some path expressions and the result of the expressions:
    在下面的表格中我们列出了一些表达式及其运行结果:

    Path Expression
    表达式
    Result
    结果
    /bookstore/* Selects all the child nodes of the bookstore element
    选取bookstore节点中的任意子节点元素
    //* Selects all elements in the document
    选取文档中的所有元素
    //title[@*] Selects all title elements which have any attribute
    选取包含任意属性的title元素


    Selecting Several Paths
    选取多个路径

    By using the | operator in an XPath expression you can select several paths.
    你可以同过在表达式中添加 | 来选取多个路径。

    Examples
    实例

    In the table below we have listed some path expressions and the result of the expressions:
    在下面的表格中我们列出了一些表达式及其运行结果:

    Path Expression
    表达式
    Result
    结果
    //book/title | //book/price Selects all the title AND price elements of all book elements
    选取book节点中的所有title和price元素
    //title | //price Selects all the title AND price elements in the document
    选取文档中的所有title和price元素
    /bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price elements in the document
    选取bookstore节点下的book节点中的所有title元素和文档中所有的price元素

    XPath Axes
    w3pop.com / 2006-09-21

    XPath 语法 XPath 操作符

    The XML Example Document
    XML文档

    We will use the following XML document in the examples below.
    我们将在下文中引用该XML文档:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>

    <title lang="eng">Harry Potter</title>
    <price>29.99</price>
    </book>
    <book>
    <title lang="eng">Learning XML</title>

    <price>39.95</price>
    </book>
    </bookstore>


    XPath Axes
    XPath 方法

    An axis defines a node-set relative to the current node.
    用于定义与单前节点相关的属性。

    AxisName
    方法名称
    Result
    结果
    ancestor Selects all ancestors (parent, grandparent, etc.) of the current node
    选取单前节点的祖类(父类,父类的父类及更多)
    ancestor-or-self Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself
    选取当前节点的祖类(父类,父类的父类及更多)和节点自身
    attribute Selects all attributes of the current node
    选取当前节点的所有属性
    child Selects all children of the current node
    选取当前节点的所有子类
    descendant Selects all descendants (children, grandchildren, etc.) of the current node
    选取当前节点的所有下属类(子类,子类的子类及更多)
    descendant-or-self Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself
    选取当前节点的所有下属类(子类,子类的子类及更多)和节点自身
    following Selects everything in the document after the closing tag of the current node
    选取文档中当前节点结束标签前的所有元素
    following-sibling Selects all siblings after the current node
    选取位于当前节点后的所有同属类节点
    namespace Selects all namespace nodes of the current node
    选取与当前节点相名的命名空间
    parent Selects the parent of the current node
    选取当前节点的父节点
    preceding Selects everything in the document that is before the start tag of the current node
    选取文档中所有位于当前节点开始标签前的元素
    preceding-sibling Selects all siblings before the current node
    选取位于当前节点前的所有同属类节点
    self Selects the current node
    选取当前节点


    Location Path Expression
    路径表达式

    A location path can be absolute or relative.
    路径表达式可以使用绝对路径也可以是相对路径。

    An absolute location path starts with a slash ( / ) and a relative location path does not. In both cases the location path consists of one or more steps, each separated by a slash:
    绝对路径表达式以(/)开始,两种路径表达式都包含一个或多个层次,用 / 分隔:

    An absolute location path:
    绝对路径:
    /step/step/...
    A relative location path:
    相对路径:
    step/step/...

    Each step is evaluated against the nodes in the current node-set.
    每个层次都对应当前节点的一个属性。

    A step consists of:
    层包括:

    • an axis (defines the tree-relationship between the selected nodes and the current node)
    • 层路径(取决于目标节点与当前节点间的目录关联)
    • a node-test (identifies a node within an axis)
    • 节点测试(确认节点包含此属性)
    • zero or more predicates (to further refine the selected node-set)
    • 无条件或条件(进一步检索节点属性)

    The syntax for a location step is:
    选取的语法为:

    axisname::nodetest[predicate]

    Examples
    实例

    Example
    实例
    Result
    结果
    child::book Selects all book nodes that are children of the current node
    选取当前节点的所有book子节点
    attribute::lang Selects the lang attribute of the current node
    选取当前节点的所有lang属性值
    child::* Selects all children of the current node
    选取当前节点的所有子节点
    attribute::* Selects all attributes of the current node
    选取当前节点的所有属性值
    child::text() Selects all text child nodes of the current node
    选取当前节点下的所有text节点的子节点
    child::node() Selects all child nodes of the current node
    选取当前节点的所有子节点
    descendant::book Selects all book descendants of the current node
    选取当前节点下所有book节点的下属类
    ancestor::book Selects all book ancestors of the current node
    选取当前节点下所有book的祖类
    ancestor-or-self::book Selects all book ancestors of the current node - and the current as well if it is a book node
    选取所有当前节点下的book祖类和book节点自身
    child::*/child::price Selects all price grandchildren of the current node
    选取所有当前节点的子节点中所包含的price元素

    XPath 操作符
    w3pop.com / 2006-09-21

    XPath Axes XPath 实例

    An XPath expression returns either a node-set, a string, a Boolean, or a number.
    XPath 表达式返回值可以是:节点属性,字符型,布尔型,数字型。


    XPath Operators
    XPath 操作符

    Below is a list of the operators that can be used in XPath expressions:
    下面给出了XPath表达式所支持的所有操作符:

    Operator
    操作符
    Description
    注释
    Example
    实例
    Return value
    返回值
    | Computes two node-sets
    连接两条语句
    //book | //cd Returns a node-set with all book and cd elements
    返回所有book和cd的节点属性
    + Addition
    6 + 4 10
    - Subtraction
    6 - 4 2
    * Multiplication

    6 * 4

    24
    div Division
    8 div 4 2
    = Equal
    price=9.80 true if price is 9.80
    false if price is 9.90
    返回true或false
    != Not equal
    不等
    price!=9.80 true if price is 9.90
    false if price is 9.80
    返回true或false
    < Less than
    小于
    price<9.80 true if price is 9.00
    false if price is 9.80
    返回true或false
    <= Less than or equal to
    小于等于
    price<=9.80 true if price is 9.00
    false if price is 9.90
    返回true或false
    > Greater than
    大于
    price>9.80 true if price is 9.90
    false if price is 9.80
    返回true或false
    >= Greater than or equal to
    大于等于
    price>=9.80 true if price is 9.90
    false if price is 9.70
    返回true或false
    or or price=9.80 or price=9.70 true if price is 9.80
    false if price is 9.50
    逻辑连接,判断两个条件中的一个
    and and price>9.00 and price<9.90 true if price is 9.80
    false if price is 8.50
    逻辑连接,同时判断两个条件
    mod Modulus (division remainder)
    求余
    5 mod 2 1

    XPath 实例
    w3pop.com / 2006-09-21

    XPath 操作符 XPath 摘要

    Let's try to learn some basic XPath syntax by looking at some examples.
    让我们通过一些实例来学习一些基础的XPath语法。


    The XML Example Document
    XML文档

    We will use the following XML document in the examples below.
    我们将在下面的例子中引用这个XML文档。

    "books.xml"文件:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book category="COOKING">
    <title lang="en">Everyday Italian</title>

    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
    </book>
    <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>

    <price>29.99</price>
    </book>
    <book category="WEB">
    <title lang="en">XQuery Kick Start</title>

    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>

    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
    </book>
    <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>

    <price>39.95</price>
    </book>
    </bookstore>

    在浏览器中查看"books.xml"文件


    Selecting Nodes
    选取节点

    We will use the Microsoft XMLDOM object to load the XML document and the selectNodes() function to select nodes from the XML document:
    我们会用Microsoft XMLDOM object来载入XML文档,用selectNodes()方法来从XML文档中选择节点。

    set xmlDoc=CreateObject("Microsoft.XMLDOM")
    xmlDoc.async="false"

    xmlDoc.load("books.xml")
    xmlDoc.selectNodes(path expression)


    Select all book Nodes
    选取所有book节点

    The following example selects all the book nodes under the bookstore element:
    下面的实例演示如何选取booksotre节点的所有book子元素:

    xmlDoc.selectNodes("/bookstore/book")

    如果你的IE是5.0以上版本,你可以自己尝试一下!


    Select the First book Node
    选取第一个book节点

    The following example selects only the first book node under the bookstore element:
    下面的例子只选择了bookstore节点的第一个book子元素:

    xmlDoc.selectNodes("/bookstore/book[0]")

    如果你的IE是5.0以上版本,你可以自己尝试一下

    Note: IE 5 and 6 has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!
    注意:IE5和IE6把[0]作为第一节点,但是在W3C标准中第一个节点是[1]!!

    Note: This is corrected in IE 6 SP2!
    注意:IE6 SP2 已经更正!


    Select the prices
    选取prices

    The following example selects the text from all the price nodes:
    下面的例子演示了如何从所有的price节点获取文本:

    xmlDoc.selectNodes("/bookstore/book/price/text()") 

    如果你的IE是5.0以上版本,你可以自己尝试一下


    Selecting price Nodes with Price>35
    选取price>35的price节点

    The following example selects all the price nodes with a price higher than 35:
    下面的例子演示了如何选取price值大于35的price节点:

    xmlDoc.selectNodes("/bookstore/book[price>35]/price") 

    如果你的IE是5.0以上版本,你可以自己尝试一下


    Selecting title Nodes with Price>35
    选取price>35的titile节点

    The following example selects all the title nodes with a price higher than 35:
    下面的例子演示了如何选取price属性值大于35的title节点:

    xmlDoc.selectNodes("/bookstore/book[price>35]/title") 

    如果你的IE是5.0以上版本,你可以自己尝试一下

    XPath 摘要
    w3pop.com / 2006-09-21

    XPath 实例 函数参考

    XPath Summary
    XPath概要

    This tutorial has taught you how to find information in an XML document.
    你已经学会了如何从一个XML文档中选取你所需要的信息。

    You have learned how to use XPath to navigate through elements and attributes in an XML document.
    你已经学会如何使用XPath语句从XML文档中寻找元素和属性。

    You have also learned how to use some of the standard functions that is built-in in XPath.
    你也学会了如何使用XPath的内置函数。

    For more information on XPath, please look at our XPath Reference.
    想了解更多的XPath,请查看我们的XPath参考。


    Now You Know XPath, What's Next?
    进一步学习XPath

    The next step is to learn about XSLT, XQuery, XLink, and XPointer.
    下一步我们将学习XSLT,XQuery,XLink和XPointer。

    XSLT

    XSLT is the style. sheet language for XML files.
    XSLT是XML文件的样式语言。

    With XSLT you can transform. XML documents into other formats, like XHTML.
    你可以用XSLT将XML文档转换成其他格式,例如XHTML。

    If you want to learn more about XSLT, please visit our XSLT tutorial.
    如果你要了解更多关于XSLT,请阅读XSLT教程。

    XQuery

    XQuery is about querying XML data.
    XQuery是XML数据的查询语句。

    XQuery is designed to query anything that can appear as XML, including databases.
    XQuery可以查询任何可以用XML呈现的数据,包括数据库。

    If you want to learn more about XQuery, please visit our XQuery tutorial.
    如果你要了解更多关于XQuery,请阅读XQuery教程。

    XLink and XPointer
    XLink 和 XPointer

    Linking in XML is divided into two parts: XLink and XPointer.
    XML中的链接分两种:XLink和XPointer。

    XLink and XPointer define a standard way of creating hyperlinks in XML documents.
    可以使用XLink和XPointer在XML文档中创建一个标准的超级链接。

    If you want to learn more about XLink and XPointer, please visit our XLink and XPointer tutorial.
    如果你要了解更多关于XLink和XPointer,请阅读XLink和XPointer教程。

    函数参考
    w3pop.com / 2006-09-21

    XPath 摘要

    The following reference library defines the functions required for XPath 2.0, XQuery 1.0 and XSLT 2.0.
    下面的参考目录库详细包括了XPath 2.0, XQuery 1.0 和 XSLT 2.0.所要求的函数


    Functions Reference
    函数参考目录

    • Accessor
    • Error and Trace
    • Numeric
    • String
    • AnyURI
    • Boolean
    • Duration/Date/Time
    • QName
    • Node
    • Sequence
    • Context

    The default prefix for the function namespace is fn:, and the URI is:
    http://www.w3.org/2005/02/xpath-functions.
    函数命名空间的默认前缀是“fn”,URI是:http://www.w3.org/2005/02/xpath-functions.

    Accessor 函数

    Name
    名称
    Description
    描述
    fn:node-name(node) Returns the node-name of the argument node
    返回自变量节点的节点(node)名称
    fn:nilled(node) Returns a Boolean value indicating whether the argument node is nilled
    返回一个逻辑值,用来指明自变量(argument)节点是否被拒绝
    fn:data(item.item,...) Takes a sequence of items and returns a sequence of atomic values
    获取项目的一个序列并返回一个原子值(atomic value)序列
    fn:base-uri()
    fn:base-uri(node)
    Returns the value of the base-uri property of the current or specified node
    返回当前节点或指定节点内基于uri属性的值
    fn:document-uri(node) Returns the value of the document-uri property for the specified node
    返回指定节点中uri文档属性的值

    Error 和 Trace 函数

    Name
    名称
    Description
    描述
    fn:error()
    fn:error(error)
    fn:error(error,description)
    fn:error(error,description,error-object)
    Example案例: error(fn:QName('http://example.com/test', 'err:toohigh'), 'Error: Price is too high')

    Result结果: Returns http://example.com/test#toohigh and the string "Error: Price is too high" to the external processing environment

    fn:trace(value,label) Used to debug queries
    用来调试查询(queries)

    Numeric 函数

    Name
    名称
    Description
    描述
    fn:number(arg) Returns the numeric value of the argument. The argument could be a boolean, string, or node-set

    Example: number('100')
    Result: 100
    返回自变量数值。这个自变量可以是一个逻辑值(boolean)、字符串(string)或者是节点设置
    举例: number('100')
    结果: 100

    fn:abs(num) Returns the absolute value of the argument
    返回自变量的绝对值

    Example举例: abs(3.14)
    Result结果: 3.14

    Example举例: abs(-3.14)
    Result结果: 3.14

    fn:ceiling(num) Returns the smallest integer that is greater than the number argument

    Example: ceiling(3.14)
    Result: 4

    fn:floor(num) Returns the largest integer that is not greater than the number argument
    返回大于自变量数值的最小整数

    Example举例: floor(3.14)
    Result结果: 3

    fn:round(num) Rounds the number argument to the nearest integer
    返回小于自变量数值的最大整数

    Example举例: round(3.14)
    Result结果: 3

    fn:round-half-to-even() Example举例: round-half-to-even(0.5)
    Result结果: 0

    Example举例: round-half-to-even(1.5)
    Result结果: 2

    Example举例: round-half-to-even(2.5)
    Result结果: 2

    Strings 函数

    Name
    名称
    Description
    描述
    fn:string(arg) Returns the string value of the argument. The argument could be a number, boolean, or node-set
    返回自变量的字符串值。这个自变量可以是一个数字、逻辑值或节点设置。

    Example举例: string(314)
    Result结果: "314"

    fn:codepoints-to-string(int,int,...) Returns a string from a sequence of code points
    从一组代码点(code points)中返回一个字符串

    Example举例: codepoints-to-string(84, 104, 233, 114, 232, 115, 101)
    Result结果: 'Thérèse'

    fn:string-to-codepoints(string) Returns a sequence of code points from a string
    从字符串中返回一组连续的代码点(code points)

    Example举例: string-to-codepoints("Thérèse")
    Result结果: 84, 104, 233, 114, 232, 115, 101

    fn:codepoint-equal(comp1,comp2) Returns true if the value of comp1 is equal to the value of comp2, according to the Unicode code point collation (http://www.w3.org/2005/02/xpath-functions/collation/codepoint), otherwise it returns false
    根据统一字符编码点整理,如果comp1值与comp2值等同,则返回true。(http://www.w3.org/2005/02/xpath-functions/collation/codepoint)反之则为false
    fn:compare(comp1,comp2)
    fn:compare(comp1,comp2,collation)
    Returns -1 if comp1 is less than comp2, 0 if comp1 is equal to comp2, or 1 if comp1 is greater than comp2 (according to the rules of the collation that is used)
    如果comp1少于comp2则返回-1,如果comp1等同于comp2或comp1
    大于comp2(根据整理规则)则返回0。 

    Example举例: compare('ghi', 'ghi')
    Result结果: 0

    fn:concat(string,string,...) Returns the concatenation of the strings
    返回字符串的串联

    Example举例: concat('XPath ','is ','FUN!')
    Result结果: 'XPath is FUN!'

    fn:string-join((string,string,...),sep) Returns a string created by concatenating the string arguments and using the sep argument as the separator
    返回一个字符串,此字符串是通过连接字符串自变量和使用解析器形式的sep自变量来创建的。

    Example举例: string-join(('We', 'are', 'having', 'fun!'), ' ')
    Result结果: ' We are having fun! '

    Example举例: string-join(('We', 'are', 'having', 'fun!'))
    Result结果: 'Wearehavingfun!'

    Example举例:string-join((), 'sep')
    Result结果: ''

    fn:substring(string,start,len)
    fn:substring(string,start)
    Returns the substring from the start position to the specified length. Index of the first character is 1. If length is omitted it returns the substring from the start position to the end
    输出一个从开始位置算起,指定长度的子字符串。第一字符索引是1.如果长度被忽略,那么就输出一个从开始位置起一直到末尾的子链。

    Example举例: substring('Beatles',1,4)
    Result结果: 'Beat'

    Example举例: substring('Beatles',2)
    Result结果: 'eatles'

    fn:string-length(string)
    fn:string-length()
    Returns the length of the specified string. If there is no string argument it returns the length of the string value of the current node
    输出指定字符串的长度。如果没有字符串自变量则返回当前节点的字符串值的长度。

    Example举例: string-length('Beatles')
    Result结果: 7

    fn:normalize-space(string)
    fn:normalize-space()
    Removes leading and trailing spaces from the specified string, and replaces all internal sequences of white space with one and returns the result. If there is no string argument it does the same on the current node
    从指定字符串中删除前端的空间与末尾的空间,用一个空格替代所有的内部空白序列。如果没有字符串自变量则在当前节点中进行上述操作。

    Example举例: normalize-space(' The   XML ')
    Result结果: 'The XML'

    fn:normalize-unicode()  
    fn:upper-case(string) Converts the string argument to upper-case
    把字符串自变量转换到upper-case 

    Example举例: upper-case('The XML')
    Result结果: 'THE XML'

    fn:lower-case(string) Converts the string argument to lower-case
    把字符串转自变量换到lower-case 

    Example举例: lower-case('The XML')
    Result结果: 'the xml'
    fn:translate(string1,string2,string3) Converts string1 by replacing the characters in string2 with the characters in string3
    通过用字符串3中的字符串替换字符串2中的字符,转换字符串1

    Example举例: translate('12:30','30','45')
    Result结果: '12:45'

    Example举例: translate('12:30','03','54')
    Result结果: '12:45'

    Example举例: translate('12:30','0123','abcd')
    Result结果: 'bc:da'

    fn:escape-uri(stringURI,esc-res) Example举例: escape-uri("http://example.com/test#car", true())
    Result结果: "http%3A%2F%2Fexample.com%2Ftest#car"

    Example举例: escape-uri("http://example.com/test#car", false())
    Result结果: "http://example.com/test#car"

    Example举例: escape-uri ("http://example.com/~bébé", false())
    Result结果: "http://example.com/~b%C3%A9b%C3%A9"

    fn:contains(string1,string2) Returns true if string1 contains string2, otherwise it returns false
    如果string 1含有string 2则输出true;反之为false

    Example举例: contains('XML','XM')
    Result结果: true

    fn:starts-with(string1,string2) Returns true if string1 starts with string2, otherwise it returns false
    如果string 1以string 2开头则输出true;反之则为false

    Example举例: starts-with('XML','X')
    Result结果: true

    fn:ends-with(string1,string2) Returns true if string1 ends with string2, otherwise it returns false
    如果string 1以string 2为结尾则输出true;反之为false

    Example举例: ends-with('XML','X')
    Result结果: false

    fn:substring-before(string1,string2) Returns the start of string1 before string2 occurs in it
    在string2触发之前输出 string1的始端

    Example举例: substring-before('12/10','/')
    Result结果: '12'

    fn:substring-after(string1,string2) Returns the remainder of string1 after string2 occurs in it
    在string2触发之前输出string1的余数

    Example举例: substring-after('12/10','/')
    Result结果: '10'

    fn:matches(string,pattern) Returns true if the string argument matches the pattern, otherwise, it returns false
    如果字符串自变量与模式相匹配则输出true,反之为false

    Example举例: matches("Merano", "ran")
    Result结果: true

    fn:replace(string,pattern,replace) Returns a string that is created by replacing the given pattern with the replace argument
    输出一个字符串(用替换自变量替换特定模式)

    Example举例: replace("Bella Italia", "l", "*")
    Result结果: 'Be**a Ita*ia'

    Example举例: replace("Bella Italia", "l", "")
    Result结果: 'Bea Itaia'
    fn:tokenize(string,pattern) Example举例: tokenize("XPath is fun", "\s+")
    Result结果: ("XPath", "is", "fun")

    anyURI 函数

    Name
    名称
    Description
    描述
    fn:resolve-uri(relative,base)  

    Boolean 函数

    Name
    名称
    Description
    描述
    fn:boolean(arg) Returns a boolean value for a number, string, or node-set
    输出一个数字、字符串及节点设置的逻辑函数
    fn:not(arg) The argument is first reduced to a boolean value by applying the boolean() function. Returns true if the boolean value is false, and false if the boolean value is true
    自变量是第一个成为适用于boolean()函数的逻辑值。如果逻辑值是false则输出true,反之亦然。

    Example举例: not(true())
    Result结果: false

    fn:true() Returns the boolean value true
    输出逻辑值为true

    Example举例: true()
    Result结果: true

    fn:false() Returns the boolean value false
    输出逻辑值为false

    Example举例: false()
    Result结果: false

    Durations、Dates 和 Times 函数

    Component Extraction Functions on Durations, Dates and Times
    持续时间、日期、时间函数组件

  • selenium测试SSL的证书问题

    2009-02-01 14:30:27

    参考文章链接:http://hi.baidu.com/bluetcw/blog/item/be5c1534b272323f5ab5f500.html

            http://www.51testing.com/?111742/action_viewspace_itemid_103239.html

    使用FF测试SSL:

    1)        下载firefox插件FF2.0remember_mismatched_domains;  FF3.0remember cetificates exception

       下载地址:FF2.0https://addons.mozilla.org/en-US/firefox/addon/2131

      FF3.0https://addons.mozilla.org/en-US/firefox/addon/10246

     

    2)        复制FFcustomProfile到脚本目录下;

           文件位置:C:\Documents and Settings\Administrator\ApplicationData\Mozilla\Firefox\Profiles\nvvxu5e6.default

    (文件名不一定为nvvxu5e6.default,但一定以.default结尾)

     

    3)        Cmd中运行命令:java -jar selenium-server.jar -multiwindow -firefoxProfileTemplate "nvvxu5e6.default"

     

    4)selenium = new DefaultSelenium("localhost", 4444, "*chrome",url);

     

    使用IE测试SSL:(当然首先要把*chrome改成*iehta
    1.
    安装上cybervillainsCA.cer,($HOME\selenium-server-0.9.2\sslSupport,确定这个证书被importthe Trusted Root certification Authorities

    2. IE Browser -> Tools -> InternetOptions ->Advaceduncheck两个选项

       1) check the publisher's certificate revocation.(检查发行商证书的吊销)

       2) Warn about certificate address mismatch(对无效站点证书发出警告)

    然后重启IE,再执行selenium脚本,那个烦人的security alert警告对话框就不会再烦人了。这样做有安全隐患,建议在虚拟机里执行,或者,执行完测试脚本后将IE恢复修改前的设置。

     

  • xpath最通俗的教程-zt

    2009-01-14 17:16:49

    xpath最通俗的教程-zt

    实例 1
    基本的XPath语法类似于在一个文件系统中定位文件,如果路径以斜线 / 开始那么该路径就表示到一个元素的绝对路径

  • Name
    名称
    Description
    描述
    fn:dateTime(date,time) Converts the arguments to a date and a time
    把自变量转换成日期和时间
    fn:years-from-duration(datetimedur) Returns an integer that represents the years component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示年份的整形
    fn:months-from-duration(datetimedur) Returns an integer that represents the months component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示月份的整形
    fn:days-from-duration(datetimedur) Returns an integer that represents the days component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示天数的整形
    fn:hours-from-duration(datetimedur) Returns an integer that represents the hours component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示时数的整形
    fn:minutes-from-duration(datetimedur) Returns an integer that represents the minutes component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示分数的整形
    fn:seconds-from-duration(datetimedur) Returns a decimal that represents the seconds component in the canonical lexical representation of the value of the argument
    输出一个在自变量值标准词汇表示中表示秒数的小数
    fn:year-from-dateTime(datetime) Returns an integer that represents the year component in the localized value of the argument
    输出一个在自变量本地值中表示年份的整形

    Example举例: year-from-dateTime(xs:dateTime("2005-01-10T12:30-04:10"))
    Result结果: 2005

    fn:month-from-dateTime(datetime) Returns an integer that represents the month component in the localized value of the argument
    输出一个在自变量本地值中表示月份的整形

    Example举例: month-from-dateTime(xs:dateTime("2005-01-10T12:30-04:10"))
    Result结果: 01

    fn:day-from-dateTime(datetime) Returns an integer that represents the day component in the localized value of the argument
    输出一个在自变量本地值中表示的整形

    Example举例: day-from-dateTime(xs:dateTime("2005-01-10T12:30-04:10"))
    Result结果: 10

    fn:hours-from-dateTime(datetime) Returns an integer that represents the hours component in the localized value of the argument
    输出一个在自变量本地值中表示时数的整形

    Example举例: hours-from-dateTime(xs:dateTime("2005-01-10T12:30-04:10"))
    Result结果: 12

    fn:minutes-from-dateTime(datetime) Returns an integer that represents the minutes component in the localized value of the argument
    输出一个在自变量本地值中表示分数的整形

    Example举例: minutes-from-dateTime(xs:dateTime("2005-01-10T12:30-04:10"))
    Result结果: 30

    fn:seconds-from-dateTime(datetime) Returns a decimal that represents the seconds component in the localized value of the argument
    输出一个在自变量本地值中表示秒数的小数

    Example举例: seconds-from-dateTime(xs:dateTime("2005-01-10T12:30:00-04:10"))
    Result结果: 0

    fn:timezone-from-dateTime(datetime) Returns the time zone component of the argument if any
    输出任何自变量时区组件如果它们存在
    fn:year-from-date(date) Returns an integer that represents the year in the localized value of the argument
    输出一个在自变量本地值中表示年份的整形

    Example举例: year-from-date(xs:date("2005-04-23"))
    Result结果: 2005

    fn:month-from-date(date) Returns an integer that represents the month in the localized value of the argument
    输出一个在自变量本地值中表示月份的整形

    Example举例: month-from-date(xs:date("2005-04-23"))
    Result结果: 4

    fn:day-from-date(date) Returns an integer that represents

    /AAA

    选择根元素AAA


         <
    AAA
              <BBB/> 
              <CCC/> 
              <BBB/> 
              <BBB/> 
              <DDD
                   <BBB/> 
              </DDD
              <CCC/> 
         </
    AAA>

     

    /AAA/CCC

    选择AAA的所有CCC子元素


         <AAA
              <BBB/> 
              <
    CCC/> 
              <BBB/> 
              <BBB/> 
              <DDD
                   <BBB/> 
              </DDD
              <
    CCC/> 
         </AAA>

     

    /AAA/DDD/BBB

    选择AAA的子元素DDD的所有子元素


         <AAA
              <BBB/> 
              <CCC/> 
              <BBB/> 
              <BBB/> 
              <DDD
                   <
    BBB/> 
              </DDD
              <CCC/> 
         </AAA>

     

     

    实例 2

    如果路径以双斜线 // 开头则表示选择文档中所有满足双斜线//之后规则的元素(无论层级关系)

     

    //BBB

    选择所有BBB元素


         <AAA
              <
    BBB/> 
              <CCC/> 
              <
    BBB/> 
              <DDD
                   <
    BBB/> 
              </DDD
              <CCC
                   <DDD
                        <
    BBB/> 
                        <
    BBB/> 
                   </DDD
              </CCC
         </AAA>

     

    //DDD/BBB

    选择所有父元素是DDDBBB元素


         <AAA
              <BBB/> 
              <CCC/> 
              <BBB/> 
              <DDD
                   <
    BBB/> 
              </DDD
              <CCC
                   <DDD
                        <
    BBB/> 
                        <
    BBB/> 
                   </DDD
              </CCC
         </AAA>

     

     

    实例 3

    星号 * 表示选择所有由星号之前的路径所定位的元素

     

    /AAA/CCC/DDD/*

    选择所有路径依附于/AAA/CCC/DDD的元素


         <AAA
              <XXX
                   <DDD
                        <BBB/> 
                        <BBB/> 
                        <EEE/> 
                        <FFF/> 
                   </DDD
              </XXX
              <CCC
                   <DDD
                        <
    BBB/> 
                        <
    BBB/> 
                        <
    EEE/> 
                        <
    FFF/> 
                   </DDD
              </CCC
              <CCC
                   <BBB
                        <BBB
                             <BBB/> 
                        </BBB
                   </BBB
              </CCC
         </AAA>

     

    /*/*/*/BBB

    选择所有的有3个祖先元素的BBB元素


         <AAA
              <XXX
                   <DDD
                        <
    BBB/> 
                        <
    BBB/> 
                        <EEE/> 
                        <FFF/> 
                   </DDD
              </XXX
              <CCC
                   <DDD
                        <
    BBB/> 
                        <
    BBB/> 
                        <EEE/> 
                        <FFF/> 
                   </DDD
              </CCC
              <CCC
                   <BBB
                        <
    BBB
                             <BBB/> 
                        </
    BBB
                   </BBB
              </CCC
         </AAA>

     

    //*

    选择所有元素


         <
    AAA
              <
    XXX
                   <
    DDD
                        <
    BBB/> 
                        <
    BBB/> 
                        <
    EEE/> 
                        <
    FFF/> 
                   </
    DDD
              </
    XXX
              <
    CCC
                   <
    DDD
                        <
    BBB/> 
                        <
    BBB/> 
                        <
    EEE/> 
                        <
    FFF/> 
                   </
    DDD
              </
    CCC
              <
    CCC
                   <
    BBB
                        <
    BBB
                             <
    BBB/> 
                        </
    BBB
                   </
    BBB
              </
    CCC
         </
    AAA>

     

     

     

    实例 4

    方块号里的表达式可以进一步的指定元素其中数字表示元素在选择集里的位置last()函数则表示选择集中的最后一个元素.

     

    /AAA/BBB[1]

    选择AAA的第一个BBB子元素


         <AAA
              <
    BBB/> 
              <BBB/> 
              <BBB/> 
              <BBB/> 
         </AAA>

     

    /AAA/BBB[last()]

    选择AAA的最后一个BBB子元素


         <AAA
              <BBB/> 
              <BBB/> 
              <BBB/> 
              <
    BBB/> 
         </AAA>

     

     

     

    实例 5

    //@id

    选择所有的id属性


         <AAA
              <BBB
     id = "b1"/> 
              <BBB
     id = "b2"/> 
              <BBB name = "bbb"/> 
              <BBB/> 
         </AAA>

     

    //BBB[@id]

    选择有id属性的BBB元素


         <AAA
              <
    BBB id = "b1"/> 
              <
    BBB id = "b2"/> 
              <BBB name = "bbb"/> 
              <BBB/> 
         </AAA>

     

    //BBB[@name]

    选择有name属性的BBB元素


         <AAA
              <BBB id = "b1"/> 
              <BBB id = "b2"/> 
              <
    BBB name = "bbb"/> 
              <BBB/> 
         </AAA>

     

    //BBB[@*]

    选择有任意属性的BBB元素


         <AAA
    查看(1569) 评论(1) 收藏 分享 管理

  • 使用loggingSelenium示例

    2009-01-14 14:40:28

    使用loggingSelenium示例:

     

    package com.selenium.demo;

     

    import com.thoughtworks.selenium.*;

    import com.unitedinternet.portal.selenium.utils.logging.*;

    import java.io.*;

    import java.io.BufferedWriter;

    import org.apache.commons.lang.*;

    import java.util.Date;

    import java.text.SimpleDateFormat;

     

    public class LogTest extends SeleneseTestCase{

        LoggingSelenium selenium;

        BufferedWriter loggingWriter;

        String url="http://mail.zzy.cn";

    //  Date now=new Date();

    //  SimpleDateFormat fnow=new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");

    //  final String resultPath = "E:\\selenium\\SRC\\testDemo";

        final String errorLog="E:\\selenium\\SRC\\testDemo\\errorLog";

        final String resultHtmlFileName = errorLog + File.separator + LoggingUtils.timeStampForFileName()+"result.html";

        final String resultEncoding = "UTF-8";

        // 覆盖setUp方法

        public void setUp() throws Exception {

           if (!new File(errorLog).exists())

           {

               new File(errorLog).mkdirs();

           }

            loggingWriter = LoggingUtils.createWriter(resultHtmlFileName, resultEncoding);

     

            LoggingResultsFormatter htmlFormatter =

                new HtmlResultFormatter(loggingWriter, resultEncoding);

            htmlFormatter.setScreenShotBaseUri("/"); // this is for linking to the screenshots

            htmlFormatter.setAutomaticScreenshotPath(errorLog);

            // wrap HttpCommandProcessor from remote-control

            LoggingCommandProcessor myProcessor =

                new LoggingCommandProcessor(new HttpCommandProcessor("localhost", 4444, "*iexplore",url), htmlFormatter);

            selenium = new LoggingDefaultSelenium(myProcessor);

           selenium.start();

        }

     

        // 覆盖teardown方法(在这里没有特别的设置)

        public void tearDown() throws Exception {

           selenium.stop();

            try {

                if (null != loggingWriter) {

                    loggingWriter.close();

                }

            } catch (IOException e) {

                // do nothing

            }

        }

     

     

     

    //截屏

    selenium.captureScreenshot(errorLog + File.separator + "ErrorScreenshot_" + LoggingUtils.timeStampForFileName()+ ".png");

     

     

     

     

    注意:

       使用loggingSelenium时,报错信息为:

    java.lang.NoClassDefFoundError: org/apache/commons/lang/ArrayUtils

    解决方案:从地址:http://commons.apache.org/lang/下载commons-lang-2.4-bin.zip

         解压后,把commons-lang-2.4.jar导入项目中

     

         

     

     

  • Selenium命令列表-zt

    2009-01-13 10:13:19

    一、  Commands (命令)

    • Action
      对当前状态进行操作
      失败时,停止测试
    • Assertion
      校验是否有产生正确的值
    • Element Locators
      指定HTML中的某元素
    • Patterns
      用于模式匹配

    1. Element Locators (元素定位器)

    • id=id
      id locator 指定HTML中的唯一id的元素 
    •  name=name
      name locator指定 HTML中相同name的元素中的第一个元素
    •  identifier=id
      identifier locator 首先查找HTML是否存在该id的元素, 若不存在,查找第一个该name的元素 
    • dom=javascrīptExpression
      dom locator用Javascrīpt表达式来定位HTML中的元素,注意必须要以"document"开头
      例如:
      dom=document.forms['myForm'].myDropdown
      dom=document.images[56]
    •  xpath=xpathExpression
      xpath locator用 XPath 表达式来定位HTML中的元素,必须注意要以"//"开头
      例如:
      xpath=//img[@alt='The image alt text']
      xpath=//table[@id='table1']//tr[4]/td[2]
    •  link=textPattern
      link locator 用link来选择HTML中的连接或锚元素
      例如:
      link=The link text
    • 在没有locator前序的情况下 Without a locator prefix, Selenium uses:
      如果以"document."开头,则默认是使用 dom locator,如果是以"//"开头,则默认使用xpath locator,其余情况均认作identifier locator

    2. String Matching Patterns (字符串匹配模式)

    • glob:patthern
      glob模式,用通配符"*"代表任意长度字符,"?"代表一个字符
    • regexp:regexp
      正则表达式模式,用Javascrīpt正则表达式的形式匹配字符串
    • exact:string
      精确匹配模式,精确匹配整个字符串,不能用通配符
    • 在没有指定字符串匹配前序的时候,selenium 默认使用golb 匹配模式

    3. Select Option Specifiers (Select选项指定器)

    • label=labelPattern
      通过匹配选项中的文本指定选项
      例如:label=regexp:^[Oo]ther
    • value=valuePattern
      通过匹配选项中的值指定选项
      例如:value=other
    • id=id
      通过匹配选项的id指定选项
      例如: id=option1
    • index=index
      通过匹配选项的序号指定选项,序号从0开始
      例如:index=2
    • 在没有选项选择前序的情况下,默认是匹配选项的文本

    二、 Actions
    描述了用户所会作出的操作。
    Action 有两种形式: action和actionAndWait, action会立即执行,而actionAndWait会假设需要较长时间才能得到该action的相响,而作出等待,open则是会自动处理等待时间。

    • click
      click(elementLocator)
      - 点击连接,按钮,复选和单选框
      - 如果点击后需要等待响应,则用"clickAndWait"
      - 如果是需要经过Javascrīpt的alert或confirm对话框后才能继续操作,则需要调用verify或assert来告诉Selenium你期望对对话框进行什么操作。
      click aCheckbox  
      clickAndWait submitButton  
      clickAndWait anyLink  
    • open
      open(url)
      - 在浏览器中打开URL,可以接受相对和绝对路径两种形式
      - 注意:该URL必须在与浏览器相同的安全限定范围之内
      open /mypage  
      open http://localhost/  
    • type
       type(inputLocator, value)
      - 模拟人手的输入过程,往指定的input中输入值
      - 也适合给复选和单选框赋值
      - 在这个例子中,则只是给钩选了的复选框赋值,注意,而不是改写其文本
      type nameField John Smith
      typeAndWait textBoxThatSubmitsOnChange newValue
    • select
      select(dropDownLocator, optionSpecifier)
      - 根据optionSpecifier选项选择器来选择一个下拉菜单选项
      - 如果有多于一个选择器的时候,如在用通配符模式,如"f*b*",或者超过一个选项有相同的文本或值,则会选择第一个匹配到的值
      select  dropDown Australian Dollars
      select  dropDown index=0
      selectAndWait currencySelector value=AUD
      selectAndWait currencySelector label=Auslian D*rs
    •  goBack,close
      goBack()
      模拟点击浏览器的后退按钮
      close()
      模拟点击浏览器关闭按钮
    • selectWindow
      select(windowId)
      - 选择一个弹出窗口
      - 当选中那个窗口的时候,所有的命令将会转移到那窗口中执行
      selectWindow myPopupWindow  
      selectWindow null  
    • pause
      pause(millisenconds)
      - 根据指定时间暂停Selenium脚本执行
      - 常用在调试脚本或等待服务器段响应时
      pause 5000  
      pause 2000  
    • fireEvent
       fireEvent(elementLocatore,evenName)
      模拟页面元素事件被激活的处理动作
      fireEvent textField focus
      fireEvent dropDown blur
    • waitForCondition
      waitForCondition(JavascrīptSnippet,time)
      - 在限定时间内,等待一段Javascrīpt代码返回true值,超时则停止等待
      waitForCondition var value="/selenium.getText(""foo"); value.match(/bar/); 3000
    • waitForValue
      waitForValue(inputLocator, value)
      - 等待某input(如hidden input)被赋予某值,
      - 会轮流检测该值,所以要注意如果该值长时间一直不赋予该input该值的话,可能会导致阻塞
      waitForValue finishIndication isfinished
           
    • store,stroreValue
      store(valueToStore, variablename)
      保存一个值到变量里。
      该值可以由自其他变量组合而成或通过Javascrīpt表达式赋值给变量
      store Mr John Smith fullname
      store $.{title} $.{firstname} $.{suname} fullname
      store javascrīpt.{Math.round(Math.PI*100)/100} PI
      storeValue inputLocator variableName

      把指定的input中的值保存到变量中

      storeValue userName userID
      type userName $.{userID}
    • storeText, storeAttribute
      storeText(elementLocator, variablename)
      把指定元素的文本值赋予给变量
      storeText currentDate expectedStartDate
      verifyValue startDate $.{expectedStartDate}

      storeAttribute(.{}elementLocator@attributeName,variableName.{)
      把指定元素的属性的值赋予给变量

      storeAttribute input1@class  classOfInput1
      verifyAttribute input2@class $.{classOfInput1}
    • chooseCancel.., answer..
      chooseCancelOnNextConfirmation()
      - 当下次Javascrīpt弹出confirm对话框的时候,让selenium选择Cancel
      - 如果没有该命令时,遇到confirm对话框Selenium默认返回true,如手动选择OK按钮一样
      chooseCancelOnNextConfirmation     

      - 如果已经运行过该命令,当下一次又有confirm对话框出现时,也会同样地再次选择Cancel
      answerOnNextPrompt(answerString)
      - 在下次Javascrīpt弹出prompt提示框时,赋予其anweerString的值,并选择确定

      answerOnNextPrompt Kangaroo  

    三、 Assertions
    允许用户去检查当前状态。两种模式: Assert 和 Verify, 当Assert失败,则退出测试;当Verify失败,测试会继续运行。

    • assertLocation, assertTitle
      assertLocation(relativeLocation)
      判断当前是在正确的页面
      verifyLocation /mypage  
      assertLocation /mypage  
    • assertTitle(titlePattern)
      检查当前页面的title是否正确
      verifyTitle My Page  
      assertTitle My Page  
    • assertValue
      assertValue(inputLocator, valuePattern)
      - 检查input的值
      - 对于 checkbox或radio,如果已选择,则值为"on",反之为"off"
      verifyValue nameField John Smith
      assertValue document.forms[2].nameField John Smith
    • assertSelected, assertSelectedOptions
      assertSelected(selectLocator, optionSpecifier)
      检查select的下拉菜单中选中的选型是否和optionSpecifer(Select选择选项器)的选项相同
      verifySelected dropdown2 John Smith
      verifySelected dorpdown2 value=js*123
      assertSelected document.forms[2].dropDown label=J*Smith
      assertSelected document.forms[2].dropDown index=0
    • assertSelectOptions(selectLocator, optionLabelList)
      - 检查下拉菜单中的选项的文本是否和optionLabelList相同
      - optionLabelList是以逗号分割的一个字符串
      verifySelectOptions dropdown2 John Smith,Dave Bird
      assertSelectOptions document.forms[2].dropdown Smith,J,Bird,D
    • assertText
      assertText(elementLocator,textPattern)
      - 检查指定元素的文本
      - 只对有包含文本的元素生效
      - 对于Mozilla类型的浏览器,用textContent取元素的文本,对于IE类型的浏览器,用innerText取元素文本
      verifyText statusMessage Successful
      assertText //div[@id='foo']//h1 Successful
    • assertTextPresent, assertAttribute
      assertTextPresent(text)
      检查在当前给用户显示的页面上是否有出现指定的文本
      verifyTextPresent You are now logged in  
      assertTextPresent You are now logged in  
    • assertAttribute(.{}elementLocator@attributeName.{, ValuePattern)
      检查当前指定元素的属性的值
      verifyAttribute txt1@class bigAndBlod
      assertAttribute document.images[0]@alt alt-text
      verifyAttribute //img[@id='foo']/alt alt-text
    • assertTextPresent, etc.
      assertTextPresent(text)
      assertTextNotPresent(text)
      assertElementPresent(elementLocator)
       verifyElementPresent   submitButton   
       assertElementPresent   //img[@alt='foo']    assertElementNotPresent(elementLocator)
    • assertTable
      assertTable(cellAddress, valuePattern)
      - 检查table里的某个cell中的值
      - cellAddress的语法是tableName.row.column, 注意行列序号都是从0开始
      verifyTable myTable.1.6 Submitted
      assertTable results0.2 13
    • assertVisible, nonVisible
      assertVisible(elementLocator)
      - 检查指定的元素是否可视的
      - 隐藏一个元素可以用设置css的'visibility'属性为'hidden',也可以设置'display'属性为'none'
      verfyVisible postcode  
      assertVisible postcode  
    • assertNotVisible(elementLocator)
       verfyNotVisible   postcode   
       assertNotVisible   postcode   
    • Editable, non-editable
      assertEditable(inputLocator)
      检查指定的input是否可以编辑
      verifyEditable shape  
      assertEditable colour  
    • assertNotEditable(inputLocator)
      检查指定的input是否不可以编辑
    • assertAlert
      assertAlert(messagePattern)
      - 检查Javascrīpt是否有产生带指定message的alert对话框
      - alert产生的顺序必须与检查的顺序一致
      - 检查alert时会产生与手动点击'OK'按钮一样的效果。如果一个alert产生了,而你却没有去检查它,selenium会在下个action中报错。
      - 注意:Selenium 不支持 Javascrīpt 在onload()事件时 调用alert();在这种情况下,Selenium需要你自己手动来点击OK.
    • assertConfirmation
      assertConfirmation(messagePattern)
      - 检查Javascrīpt是否有产生带指定message的confirmation对话框和alert情况一样,confirmation对话框也必须在它们产生的时候进行检查
      - 默认情况下,Selenium会让confirm() 返回true, 相当于手动点击Ok按钮的效果。你能够通过chooseCancelOnNextConfirmation命令让confirm()返回false.同样地,如果一个cofirmation对话框出现了,但你却没有检查的话,Selenium将会在下个action中报错
      - 注意:在Selenium的环境下,confirmation对话框框将不会再出现弹出显式对话框
      - 注意:Selenium不支持在onload()事件时调用confirmation对话框,在这种情况下,会出现显示confirmatioin对话框,并需要你自己手动点击。
    •  assertPrompt
      assertPrompt(messagePattern)
      - 检查Javascrīpt是否有产生带指定message的Prompt对话框
      - 你检查的prompt的顺序Prompt对话框产生的顺序必须相同
      - 必须在verifyPrompt之前调用answerOnNextPrompt命令
      - 如果prompt对话框出现了但你却没有检查,则Selenium会在下个action中报错
      answerOnNextPrompt Joe  
      click id=delegate  
      verifyPrompt Delegate to who?  

    四、 Parameters and Variables
    参数和变量的声明范围由简单的赋值到Javascrīpt表达式赋值。
    Store,storeValue 和storeText 为下次访问保存值。
    在Selenium内部是用一个叫storeVars的map来保存变量名。

    • Variable Substitution 变量替换
      提供了一个简单的方法去访问变量,语法 $.{xxx}
      store Mr title
      storeValue nameField surname
      store $.{title} $.{suname} fullname
      type textElement Full name is: $.{fullname}
    •  Javascrīpt Evaluation Javascrīpt赋值
      你能用Javascrīpt来构建任何你所需要的值。
      这个参数是以javascrīpt开头,语法是 javascrīpt.{'with a trailing'}。
      可以通过Javascrīpt表达式给某元素赋值。
      store javascrīpt.{'merchant'+(new Date()).getTime()} merchantId
      type textElement javascrīpt.{storedVars['merchantId'].toUpperCase()}
    • Generating Unique values 产生唯一值.  
      问题:你需要唯一的用户名
      解决办法: 基于时间来产生用户名,如'fred'+(new Date().getTime())