How to get the count of likes from a Twitter post using Selenium?

726 Views Asked by At

I'm trying to find a way to get the likes counter from any given Twitter post.

For example, this tweet: https://twitter.com/whale_alert/status/1508925640745140232

I have tried using every element around that text with no success.

What should I call on to get the like counter from tweets?

1

There are 1 best solutions below

0
On

The element with number of likes is left to the element with text as Likes.

To extract the number of likes you need to induce WebDriverWait for the visibility_of_element_located() and you can use the relative Left of locator strategy:

  • Using XPATH and RelativeBy(object):

    driver = webdriver.Chrome(service=s, options=options)
    driver.get('https://twitter.com/whale_alert/status/1508925640745140232')
    likes = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[text()='Likes']")))
    likes_count = driver.find_element(locate_with(By.TAG_NAME, "span").to_left_of(likes))
    print(likes_count.text)
    
  • Console Output:

    87
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.relative_locator import locate_with
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

tl; dr

Selenium 4 - Relative Locators