Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

Python BeautifulSoup: How to Find Last Occurrence of Tag with Specific Attribute

How can you find the last occurrence of a tag with this attribute: data-index without having the value of it?

I have written the code below but it returns IndexError: list index out of range although the list is not empty.

soup.find_all(attrs={"data-index"})[-1]

Thanks in advance! 😉

Upvotes: 1

Views: 1425

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195553

Change the set attrs={"data-index"} to dict attrs={"data-index":True}:

data = '''<div>
 <div>
   <div data-index="1">xxx</div>
 </div>

 <div>
   <div data-index="2">xxx</div>
 </div>

 <div>
   <div data-index="3">xxx</div>
 </div>
</div>
'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')
print(soup.find_all(attrs={"data-index":True})[-1])

Prints:

<div data-index="3">xxx</div>

Or with CSS selectors:

print(soup.select('[data-index]')[-1])

Upvotes: 3

Related Questions