nolan
nolan

Reputation: 63

Get a specific attribute from a class name with selenium

I am trying to get only the values of specific attributes ("Followers", "Followings", "Likes") with Selenium.

inspector

I have tried the following

following = driver.find_element(By.XPATH, "//span[@class='number']").get_attribute("Following")
followers = driver.find_element(By.XPATH, "//span[@class='number']").get_attribute("Followers")
likes = driver.find_element(By.XPATH, "//span[@class='number']").get_attribute("Likes")

but it does not return anything after printing it.

In my case, I want only the values: 0 , 98, 73

Upvotes: 0

Views: 527

Answers (1)

art_architect
art_architect

Reputation: 929

There are 3 elements having the same class, you have to differentiate them or create different xpaths to point to the specific elements. You want to take the text of that element or the innerText attribute:

#version 1 using text
following = driver.find_element(By.XPATH, "//strong[@title='Following']").text
followers = driver.find_element(By.XPATH, "//strong[@title='Followers']").text
likes = driver.find_element(By.XPATH, "//strong[@title='Likes']").text

print (following, followers,likes)

#version 2 using attribute innerText
following_attribute_innerText = driver.find_element(By.XPATH, "//strong[@title='Following']").get_attribute("innerText")
followers_attribute_innerText = driver.find_element(By.XPATH, "//strong[@title='Followers']").get_attribute("innerText")
likes_attribute_innerText = driver.find_element(By.XPATH, "//strong[@title='Likes']").get_attribute("innerText")

print (following_attribute_innerText, followers_attribute_innerText,likes_attribute_innerText)

#other way to get the xpath using the parent class
following_other_xpath = driver.find_element(By.XPATH, "//div[@class='number']/strong[@title='Following']").text
followers_other_xpath = driver.find_element(By.XPATH, "//div[@class='number']/strong[@title='Followers']").text
likes_other_xpath = driver.find_element(By.XPATH, "//div[@class='number']/strong[@title='Likes']").text

print (following_other_xpath, followers_other_xpath,likes_other_xpath)

Upvotes: 2

Related Questions