1

I have three elements with the same button class and span class names. I wanted to use xpath to select the second span class but I always get it wrong.

I used:

browser.find_element(By.XPATH, "/html/body/div[1]/div/div[3]/main/div[3]/div[2]/div[2]/div/div/section[2]/div[2]/form/div[9]/button/span[1]").click()

But I get error. I also tried the following but get the same error message.

result = browser.find_elements(By.XPATH, "//button[@class='_1h5on2Eq5J']")[2].click()
browser.switch_to.frame(result)
results = browser.find_element(By.XPATH, "/html/body/div[1]/div/div[3]/main/div[3]/div[2]/div[2]/div/div/section[2]/div[2]/form/div[9]/button/span[1]")

Below is an excerpt of the html. My interest is to find the second element.

enter image description here

Michael Mintz
16.1k9 gold badges51 silver badges109 bronze badges
asked Dec 27, 2022 at 18:13
4
  • 1
    Does this answer your question? How to access the second element that has the same class name in selenium Commented Dec 27, 2022 at 18:14
  • Use your browser's Inspect Element feature to get the exact xpath of that element. What is the difficulty? Commented Dec 27, 2022 at 18:16
  • @JohnGordon: In my experience, this doesn't always work. Some of these paths are ridiculously long, incredibly specific, and often return nothing when you try to use them. So you still have to be smart with your xpath. Commented Dec 27, 2022 at 18:23
  • @stdunbar. I tried your solution earlier but did not work Commented Dec 27, 2022 at 19:55

1 Answer 1

2

You can use xpath to find text that contains a substring.

Here's the selector you would want for the "Expand" button:

"//button//span[contains(., 'Expand')]"
answered Dec 27, 2022 at 18:20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.