Thamizhmani
Thamizhmani

Reputation: 1

How to click the last found text in webpage using python selenium

On Webpage,

There are so many texts with same name

Example

  1. Explore
  2. Explore
  3. Explore
  4. Explore
  5. Explore

I want to click the 5th or 4th

Note: The count varies every time, when I reload the webpage

  1. Explore
  2. Explore
  3. Explore
  4. Explore
  5. Explore
  6. Explore
  7. Explore

I want to click the 6th or 7th text.

Please give solution:

Using the below syntax: not working driver.find_elements_by_xpath("//*[contains(text(), 'Explore')]")

Upvotes: 0

Views: 37

Answers (2)

yong
yong

Reputation: 13722

You can use Python slice feature, get the last two Explore, and get the only Explore if there is only one Explore

eles = driver.find_elements_by_xpath("//*[contains(., 'Explore')]")

for ele in eles[-2:]:
  ele.click()

Upvotes: 0

Maciej.O
Maciej.O

Reputation: 103

Try select this element by CSS - Selector for example if your 'EXPLORE' element is a paragraph:

locator = (By.CSS_SELECTOR,'p *:last-child')

# Alternative 
# locator = (By.CSS_SELECTOR,'p:last-child')

# Alternative
# locator = (By.XPATH,"//p[contains(text(),'Explore')][last()]")

def click_button(self, *locator):
   button = self.driver.find_element(*locator)
   button.click()

If you would like click pre-last element :

locator = (By.CSS_SELECTOR,'p:nth-last-child(2)')

I hope it will be helpfull.

Upvotes: 1

Related Questions