Nabil Mustofa
Nabil Mustofa

Reputation: 72

How to click on like/dislike button of YouTube video using selenium webdriver python?

enter image description heremy code :

react_on_video = (input("React: ")).upper()
video_link = "https://www.youtube.com/watch?v=blablabla"

(After login with my gmail account)

driver.get(video_link)
driver.execute_script("window.scrollTo(0, 300);")
time.sleep(1)
if react_on_video == "LIKE":
    Like_button_Full_xpath = "/html/body/ytd-app/div/ytd-page-manager/ytd-watch- 
          flexy/div[5]/div[1]/div/div[8]/div[2]/ytd-video-primary-info- 
          renderer/div/div/div[3]/div/ytd-menu-renderer/div[1]/ytd-toggle-button-renderer[1]/a/yt- 
          icon-button/button/yt-icon"
    driver.find_element_by_xpath(Like_button_Full_xpath).click()
    
if react_on_video == "DISLIKE":
    Dislike_button_Full_xpath = "/html/body/ytd-app/div/ytd-page-manager/ytd-watch- 
          flexy/div[5]/div[1]/div/div[8]/div[2]/ytd-video-primary-info- 
          renderer/div/div/div[3]/div/ytd-menu-renderer/div[1]/ytd-toggle-button-renderer[2]/a/yt- 
          icon-button/button/yt-icon"
    driver.find_element_by_xpath(Dislike_button_Full_xpath).click()

But every time it shows No such element exception! [selenium.common.exceptions.NoSuchElementException: Message: no such element:] I've tried with other selectors and xpaths; but none of them worked! Is there any permanent solution? Because once I was able to click on the buttons with this xpath. I had to change xpath multiple times. Like_button_xpath : '//[@id="top-level-buttons"]/ytd-toggle-button-renderer1/a'
Dislike_button_xpath : '//
[@id="top-level-buttons"]/ytd-toggle-button-renderer[2]/a'

Upvotes: 0

Views: 1529

Answers (2)

Dai Tran
Dai Tran

Reputation: 86

I found Solution. Try xPath

Like_button_Full_xpath = "//div[3]/div/ytd-menu-renderer/div/ytd-toggle-button-renderer/a/yt-icon-button/button/yt-icon"

Tell me if it work.

Upvotes: 2

C. Peck
C. Peck

Reputation: 3717

Instead of using xpath, I would use a css selector. I can't guarantee that this selector will be unique without seeing the full HTML, but I would try finding the "Like" button like this:

driver.find_element_by_css_selector('yt-icon.style-scope.ytd-toggle-button-renderer')

Upvotes: 0

Related Questions