Gintade
Gintade

Reputation: 25

How to access last element in a web page when everything has the same class?

I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

Upvotes: 1

Views: 461

Answers (3)

frianH
frianH

Reputation: 7563

Use last():

message = self.driver.find_element_by_xpath("(//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')])[last()]")

Upvotes: 0

chaha0s
chaha0s

Reputation: 128

Use find_elements_by_xpath to do this.It will return a list of matching WebElements.After this you can access the last element by using list[-1]

message = self.driver.find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")
print(message[-1].text)

Docs

Upvotes: 0

Guy
Guy

Reputation: 50899

You can use find_elements_by_xpath to get a list of all the elements matching the locator and take the last item on that list

all_messages = self.driver.find_elements_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
message = all_messages[-1]

By the way you can simplify the xpath to

find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")

Or use css_selector instead

find_elements_by_css_selector('.markup-2BOw-j.containerCozy-336-Cz.markupRtl-3M0hmN')

Upvotes: 2

Related Questions