8-02-工作琐事

Xpath // Trap

I am trying to loacte a attr element in a label context using capybara. The html looks like:

1
2
3
4
5
6
7
8
9
...
<div class="post">
<label for="post_name">
Name<attr title="required">*</attr>
</label>
</div>
...

And I use the code like:

1
2
3
4
5
6
within "div.post"
label = page.find "label", "Name"
label.find :xpath, "//attr[@title=\"required\"]"
end

As usual, I’m pretty sure that the find will work like:

1
//label//attr

the find search the xpath in label context and find it.

Quite easy but I’m wrong.

In XPath the expression // means something very specific, and it might not be what you think.
Contrary to common belief, // means anywhere in the document not anywhere in the current context.
As an example:

1
page.find(:xpath, '//body').all(:xpath, '//script')

You might expect this to find all script tags in the body,
but actually, it finds all script tags in the entire document,
not only those in the body! What you’re looking for is the .// expression which means “any descendant of the current node”:

1
page.find(:xpath, '//body').all(:xpath, './/script')

The same thing goes for within:

1
2
3
4
5
6
within(:xpath, '//body') do
page.find(:xpath, './/script')
within(:xpath, './/table/tbody') do
...
end
end

You can refer to capybara document

And also there is a great post: Using “//“ And “.//“ Expressions In XPath XML Search Directives In ColdFusion

文章目录
  1. 1. Xpath // Trap
|