Home > Net >  Find when a Youtube video was uploaded using Selenium (python)
Find when a Youtube video was uploaded using Selenium (python)

Time:06-05

I'm writing a script in python to go to a url that will show new YouTube videos, I'm wanting to find a video that says it was uploaded "3 minutes ago" and then print something in my console. Example of mins ago

I found this piece of Javascript code from a while ago, I'm not sure if this would be possible to be translated into Python code or not though. It finds a video that was uploaded from 3 minutes and under, meaning if a video was uploaded 2, 1 mins ago, or seconds ago, it will click on it.

var Link = iimGetLastExtract(2);
if (Link.indexOf("&") > -1) Link = Link.split("&")[0];

if (iimGetLastExtract(1).trim() == "2 minutes ago" || iimGetLastExtract(1).trim() == "1 minute ago" || iimGetLastExtract().indexOf("second") > -1)

Does anyone know how I could do this in Python? My code is below (not working since I don't know how to do this).

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

find_timeago = driver.find_element(By.XPATH, '//*[@id="metadata-line"]/span[2]')

while True:
    if find_timeago == "3 minutes ago":
        print('found video from 3 mins ago')
    elif find_timeago == "1 minute ago":
        print('found video from 3 mins ago')
    elif find_timeago == "seconds ago": 
        print('found video from seconds ago')
    else:
        time.sleep(2)
        driver.refresh()

CodePudding user response:

If your code for finding the span is correct, the code you should use is

find_timeago = driver.find_element(By.XPATH, '//*[@id="metadata-line"]/span[2]').text

instead of

find_timeago = driver.find_element(By.XPATH, '//*[@id="metadata-line"]/span[2]')

P.S. You nearly always want .text or .find_element behind the result

And(though I don't know about YouTube), you don't need to use selenium, requests with headers is nearly always enough.

CodePudding user response:

if your js code is correct you can simply use it without having to translate it to python

js code

var Link = iimGetLastExtract(2);
if (Link.indexOf("&") > -1) Link = Link.split("&")[0];

if (iimGetLastExtract(1).trim() == "2 minutes ago" || iimGetLastExtract(1).trim() == "1 minute ago" || iimGetLastExtract().indexOf("second") > -1){
return iimGetLastExtract(1).trim()}

python code

x = driver.execute_script(js_code)
print(x)

x should hold what ever value evaluated to correct

  • Related