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.
Michael Mintz
16.1k9 gold badges51 silver badges109 bronze badges
-
1Does this answer your question? How to access the second element that has the same class name in seleniumstdunbar– stdunbar2022年12月27日 18:14:52 +00:00Commented 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?John Gordon– John Gordon2022年12月27日 18:16:41 +00:00Commented 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.Robert Harvey– Robert Harvey2022年12月27日 18:23:52 +00:00Commented Dec 27, 2022 at 18:23
-
@stdunbar. I tried your solution earlier but did not workuser16794957– user167949572022年12月27日 19:55:19 +00:00Commented Dec 27, 2022 at 19:55
1 Answer 1
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
Michael Mintz
16.1k9 gold badges51 silver badges109 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
default