Reputation: 1
On Webpage,
There are so many texts with same name
Example
I want to click the 5th or 4th
Note: The count varies every time, when I reload the webpage
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
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
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