Search code examples
pythonseleniumautomationwebautomation

YouTube automation with selenium and python, problem in selecting from the searched video


Currently I am working on automation of Youtube with Python and Selenium, after searching on Youtube. I want to select from the searched video per user demands i.e first video, the second or third video, etc. But I tried almost all selectors, they have the same attributes, they play the first video. So if you have any solution then reply. Thanks in advance! The diagram is attached below:) CODE:

select_video1=driver.find_element_by_xpath('//*[@id="video-title"]/yt-formatted-string')
select_video1.click()

The diagram:

Image is here


Solution

  • The below should work:

    driver.get("https://www.youtube.com/results?search_query=decorater")
    
    video_number = 2
    
    driver.find_element_by_xpath(f"(//a[@id='video-title'])[{video_number}]").click()
    

    This uses f-strings so you can make the value dynamic. Just change video_number to whichever video you want to play in the list