Home > Software engineering >  How to always select the highest available quality on youtube video with selenium
How to always select the highest available quality on youtube video with selenium

Time:05-31

driver.find_element(By.CSS_SELECTOR, value='button.ytp-button.ytp-settings-button').click()
time.sleep(1)
driver.find_element(By.XPATH, value="/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[1]/div/div/div/ytd-player/div/div/div[30]/div/div/div[3]").click()

Some videos have their highest quality 1080p, others have 1440p and others have 4k and so on, how do I make selenium click the on that is the highest.

I was thinking of doing something like to append all the qualites available to a list and then just go with the list[0] or list[-1]. Depends what index does the highest available quality takes.

Example1

Example2

CodePudding user response:

If you are looking to set the maximum available resolution (or the top one), you don't need to rely on strings defining the resolutions. Just click the first button that exists. Also, the answer you posted isn't a good practice (use loops instead)

driver.find_element(By.XPATH, value='(//div[@])[1]').click()

enter image description here

CodePudding user response:

try:
    driver.find_element(By.XPATH, value="//span[contains(string(),'2160p')]").click()
except NoSuchElementException:
    try:
        driver.find_element(By.XPATH, value="//span[contains(string(),'1440p')]").click()
    except NoSuchElementException:
        try:
            driver.find_element(By.XPATH, value="//span[contains(string(),'1080p')]").click()
        except NoSuchElementException:
            try:
                driver.find_element(By.XPATH, value="//span[contains(string(),'720p')]").click()
            except NoSuchElementException:
                try:
                    driver.find_element(By.XPATH, value="//span[contains(string(),'480p')]").click()
                except NoSuchElementException:
                    try:
                        driver.find_element(By.XPATH, value="//span[contains(string(),'360p')]").click()
                    except NoSuchElementException:
                        try:
                            driver.find_element(By.XPATH, value="//span[contains(string(),'240p')]").click()
                        except NoSuchElementException:
                            try:
                                driver.find_element(By.XPATH, value="//span[contains(string(),'144p')]").click()
                            except NoSuchElementException:
                                print("App has crashed")  # Do not think code can reach here, but just in case
                                exit()

Did this should be good, if there is something "faster" would be appreciated.

  • Related