Home > Mobile >  How to locate and click on the play button in spotify using Selenium
How to locate and click on the play button in spotify using Selenium

Time:08-24

I have been trying to make selenium play a specific song from a specific link but when done so on a new account, it just doesn't want to interact and gives me the:

could not locate the element

exception even though its visible, rendered (I can click on it manually) and I used different methods like xpath and class name (I'm stuck with css selector because it worked enough for me to this point). Here's the snippet of a part from this script since anything before it was just logging in, all of the modules I imported and some credentials I want to keep private like my emails and stuff:

driver.get('https://open.spotify.com/track/0WSEq9Ko4kFPt8yo3ICd6T?si=e2c993506d17435b&nd=1')
time.sleep(3)
driver.refresh()
time.sleep(2)
driver.find_element_by_class_name('PFgcCoJSWC3KjhZxHDYH').click

CodePudding user response:

This will locate the element for you:

playbutton = driver.find_element(By.XPATH, '//button[@data-testid="play-button"]')

It's not pure selenium, but something like this should work for the click:

playbutton = driver.find_element(By.XPATH, '//button[@data-testid="play-button"]')
driver.execute_script("arguments[0].click();", playbutton)

CodePudding user response:

To click on the Play button on the Spotify page, you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    driver.get('https://open.spotify.com/track/0WSEq9Ko4kFPt8yo3ICd6T?si=e2c993506d17435b&nd=1')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#onetrust-close-btn-container button[aria-label='Close']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[data-testid='action-bar-row'] button[data-testid='play-button'][aria-label='Play']"))).click()
    
  • Using XPATH:

    driver.get('https://open.spotify.com/track/0WSEq9Ko4kFPt8yo3ICd6T?si=e2c993506d17435b&nd=1')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='onetrust-close-btn-container']//button[@aria-label='Close']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@data-testid='action-bar-row']//button[@data-testid='play-button' and @aria-label='Play']"))).click()
    
  • Note: You have to add the following imports :

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

CodePudding user response:

try this class name: Button-qlcn5g-0 kgFBvD.

Or you can just copy xpath and use find_element_by_xpath()

  • Related