4

I have a query for a one of my tests that returns 2 results. Specifically the 3rd level of an outline found using

query = html("ul ol ul")

How do I select the first or second unordered list?

query[0]

decays to a HTMLElement

list(query.items())[0]

or

query.items().next() #(in case of the first element)

is there any better way that I can't see?

note:

query = html("ul ol ul :first")

gets the first element of each list not the first list.

2 Answers 2

6
+50

From the PyQuery documentation on traversing, you should be able to select the first unordered list by using:

query('ul').eq(0)

Thus the second unordered list can be obtained by using:

query('ul').eq(1)
2
  • 1
    Why did they pick eq? such a bad name, makes me think of ==/__eq__ Apr 15, 2014 at 8:43
  • 1
    Agreed. Completely counter-intuitive.
    – Talvalin
    Apr 15, 2014 at 8:53
2

In jQuery one would use

html("ul ol ul").first()

.first() - Reduce the set of matched elements to the first in the set.

or

html("ul ol ul").eq(0)

.eq() - Reduce the set of matched elements to the one at the specified index.

1
  • 1
    True, but PyQuery doesn't support the first wayt unfortunately.
    – Pithikos
    Jul 21, 2017 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.