XPath Flashcards

1
Q

Что такое нода?

XPath

A
  • element,
  • attribute,
  • text,
  • namespace,
  • processing-instruction,
  • comment,
  • root nodes.

XML documents are treated as trees of nodes.
The topmost element of the tree is called the root element.

<bookstore>
  <book>
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>

bookstore - root node
author - element node
lang - attribute node

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Выбрать все ноды bookstore

XPath

A

nodename

Selects all nodes with the name “nodename”

Пример: bookstore

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Выбор от корневой ноды

XPath

A

/ - выбирает корневые ноды

Пример /bookstore

Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Выбрать все ноды book

XPath

A

// - выбирает ноды в документе от текущей ноды которые подходят по имени не смотря на положение в документе

Пример: //book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Выбрать текущую ноду

XPath

A

. - выбирает текущую ноду

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Выбрать родителя текущей ноды

XPath

A

.. - выбирает родителя текущей ноды

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Выбрать атрибут

XPath

A

@ - выбирает атрибуты

//@lang - выбирает все атрибуты lang

Альтернатива:
//*[@id='Element ID']

Examples
//*[@id="Element ID"] will select any element with id=”cool”
//ul[@id="long"] will select <ul id="long">

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Выбрать все дочерние элементы book ноды bookstore

XPath

A

bookstore/book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Выбрать всех наследников book ноды bookstore независимо от положения внутри

XPath

A

bookstore//book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Wildcard. Любой элемент ноды

XPath

A

* - Matches any element node

/bookstore/* - выбирает все дочерние элементы ноды

//* - выбирает все элементы в документе

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Wildcard. Найти все атрибуты

XPath

A

@* - Matches any attribute node

//title[@*] - выбирает все элементы title у которых есть хотябы один любой атрибут

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Wildcard. Найти ноду любого типа

XPath

A

node() - Matches any node of any kind

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Выбрать одновременно title и price внутри book

XPath

A

By using the '|' operator in an XPath expression you can select several paths.

//book/title | //book/price - Selects all the title AND price elements of all book elements

//title | //price - Selects all the title AND price elements in the document

/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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Select all ancestors (parent, grandparent, etc.) of the current node

XPath Axes

A

ancestor

ancestor::book - Selects all book ancestors of the current node

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself

XPath Axes

A

ancestor-or-self

ancestor-or-self::book - Selects all book ancestors of the current node - and the current as well if it is a book node

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Selects all attributes of the current node

XPath Axes

A

attribute

attribute::lang - Selects the lang attribute of the current node

attribute::* - Selects all attributes of the current node

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Selects all children of the current node

XPath Axes

A

child

child::book - Selects all book nodes that are children of the current node

child::* - Selects all element children of the current node

child::text() - Selects all text node children of the current node

child::node() - Selects all children of the current node

child::*/child::price - Selects all price grandchildren of the current node

18
Q

Selects all descendants (children, grandchildren, etc.) of the current node

XPath Axes

A

descendant

descendant::book - Selects all book descendants of the current node

19
Q

Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself

XPath Axes

A

descendant-or-self

20
Q

Selects everything in the document after the closing tag of the current node

XPath Axes

A

following

21
Q

Selects all siblings after the current node

XPath Axes

A

following-sibling

//A/following-sibling::B

Examples
//p/following-sibling::div will select every element with <div> that directly follows a p
//div//following-sibling::a will select every a element that directly follows a div

22
Q

Selects all namespace nodes of the current node

XPath Axes

A

namespace

23
Q

Selects the parent of the current node

XPath Axes

A

parent

23
Q

Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes

XPath Axes

A

preceding

24
Q

Selects all siblings before the current node

XPath Axes

A

preceding-sibling

//A/preceding-sibling::B

Examples
//p/preceding-sibling::div will select every element with <div> that directly precends a p

25
Q

Selects the current node

XPath Axes

A

self

26
Q

Location Path Expression

XPath Axes

A

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:

  1. an axis (defines the tree-relationship between the selected nodes and the current node)
  2. a node-test (identifies a node within an axis)
  3. zero or more predicates (to further refine the selected node-set)

The syntax for a location step is:
axisname::nodetest[predicate]

27
Q

Select the title of the first book

A

/bookstore/book[1]/title

28
Q

Select price nodes with price>35

A

/bookstore/book[price>35]/price

29
Q

Select title nodes with price>35

A

/bookstore/book[price>35]/title

30
Q

Class selector

XPath

A

Должно работать //*[@class, 'value']

//*[contains(@Attribute,'value')]

//*[contains(@class,"neato")] selects all elements with class=”neato”

31
Q

Index Selector

XPath

A

Select element at given index
(A)[Index] - counting from 0
You can select a specific element given within a xpath result.

Examples
(//a)[2] will select second A

32
Q

Select last selector

XPath

A

Select the last element inside of another element
[last()]
You can use this selector to select an element that is the last child element inside of another element.

Pro Tip → In cases where there is only one element, that element counts as the first-child, only-child and last-child!

Examples
(//div)[last()] selects the last <div> element.
//div/*[last()] selects all the last elements within <div> elements.

33
Q

Last - N selector

XPath

A

Select the second last element inside of another element
//A[last()-N]
You can use this selector to select an element that is the last - N child element inside of another element.
Examples
(//div)[last()-3] selects the 4th last <div> element.

34
Q

Multiple Attribute Value Selector

XPath

A

Select all elements that have multiple specific attribute value
//B[@attribute='value' and @otherAttribute='other value']/A
Attribute selectors are case sensitive, each character must match exactly.
Examples
//input[@type="text" and @placeholer="username"] selects all text input elements with placeholder username.

35
Q

Attribute Starts With Selector

A

Select all elements with an attribute value that starts with specific characters
//*[starts-with(@attribute,"value")]
Examples
//toy[starts-with(@category,"Swim")] selects elements with class toy and category “Swimwear”

36
Q

Attribute Ends With Selector

A

Select all elements with an attribute value that ends with specific characters. The ‘ends-with’ function is part of xpath 2.0 but browsers generally only support 1.0
//*[substring(@attribute, string-length(@attribute) - string-length('end text') +1) = 'end text']
Examples
//img[substring(@src, string-length(@src) - string-length('.jpg')+1 ) '.jpg' ] selects all images display a .jpg image.

37
Q

Поиск по текту

XPath

A

//a[.='Текст ссылки'] - точка это текстовое содержимое выбранного элемента

contains() - по части текста

//h1[contains(text(),’ Log in to Twitter’)]

starts-with() - начинается с текста
//h1[starts-with(text(),’Log in’)]

text() - весь текст
//h1[text()='Log in to Twitter']

38
Q

Удаление лишних пробелов в строке

XPath

A

normalize-space()

<div class="btn">Войти через Google</div>

Плохая практика
//[text()=’Войти через Google’]

Хорошая практика
//[normalize-space(text())=’Войти через Google’]

Почему: Последний селектор нивелирует ошибки в верстке, связанные с пробелами. Например, это спасет в подобной ситуации:

<div class="btn"> Войти через Google </div>

<div class="btn"> Войти     через  Google </div>

__

 <a class="Menu_item\_\_5wCCC">Карта</a>
 
//a[normalize-space(.)=’Карта’]
39
Q

Использование поиска по вложенному тексту (.)

A

Для тегов <h1>-<h6>, <a>, <button>, <li>, <td> по возможности необходимо использовать поиск по вложенному тексту (.), а не по text().

Код:

<button jsname="pzCKEc" class="EzVRq" aria-controls="dEjpnf" aria-haspopup="true">Настройки</button>

Плохая практика //button[normalize-space(text())='Настройки']

Хорошая практика: //button[normalize-space(.)='Настройки']

Почему: Разработчик в любой момент может обернуть текст внутри в какой-нибудь <span>, и тогда поиск по text() не будет работать. Бывает, что фреймворки не могут кликнуть по вложенному тегу, иногда это приводит к ошибкам перехвата клика элементом уровнем выше. Если же искать по вложенному тексту, все эти проблемы перестают быть опасными.</span>

40
Q

Подзапросы (вместо подъема по дереву)

XPath

A

//form[./input[@id='test2']] - найти такую форму, внутри которой находится input с идентификатором

Является альтернативой для //input[@id='test2']/..