Home > Software design >  How to get the different values from two elements with the same class in Selenium in Python?
How to get the different values from two elements with the same class in Selenium in Python?

Time:11-24

I have an HTML code like this:

<span class="twitter-label">
Connect Your Twitter Account
</span>

and 

<span class="twitter-label">
Follow
</span>

How can I take the second class name?

CodePudding user response:

You can use driver.find_elements with "By.CLASS_NAME":

from selenium.webdriver.common.by import By

lst = driver.find_elements(By.CLASS_NAME, 'twitter-label')

This gives you the list of span elements whose class name is "twitter-label". You can have the second element in the list with lst[1] and it's text with lst[1].text, or click it with lst[1].click().

If you are not sure that it's the second element with taht specification, you can also check it's text or use "By.XPATH" to consider if it contains 'follow' in it's text.

CodePudding user response:

You can use the .find_elements_by_class_name("twitter-label"), it's plural, it will return a list of the elements found. So you can access which one want:
To access the Connect use:

driver.find_elements_by_class_name("twitter-label")[0].click()

To access the Follow use:

driver.find_elements_by_class_name("twitter-label")[1].click()

Edit:
The find_elements_by_* functions are deprecated, you should update to find_elements().
You want to find a class, so you need to pass that as the first argument to the function, and then the name of the class you want to find.
So it should look like this:

driver.find_elements(By.CLASS_NAME, "twitter-label")[0].click()
  • Related