Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the first item(or xth item) in a PyQuery query?

Tags:

python

pyquery

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.

like image 284
Roman A. Taycher Avatar asked Oct 20 '25 14:10

Roman A. Taycher


2 Answers

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)
like image 177
Talvalin Avatar answered Oct 22 '25 04:10

Talvalin


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.

like image 30
CodeManX Avatar answered Oct 22 '25 04:10

CodeManX