【问题标题】:How to return the link to the first Youtube video after a search in Selenium Python?如何在 Selenium Python 中搜索后返回第一个 Youtube 视频的链接?
【发布时间】:2021-04-07 11:17:39
【问题描述】:

我正在尝试创建一个函数,该函数从列表中获取搜索词并将其添加到链接列表中。

formatted_link = link_to_vid.replace(' ', '+')
driver.get('https://www.youtube.com/results?search_query={}'.format(str(formatted_link)))

然后提取 YouTube 返回的第一个链接。例如,我搜索“Never Gonna Give You Up”,它会将第一个结果的链接添加到列表中。

那我可能想做['Never Gonna Give You Up', 'Shrek']

如果不实际点击链接,我该怎么做?

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    我希望你的问题是正确的,这里有一个例子:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    
    # Let's create a list of terms to search for and an empty list for links
    search_terms = ['Never Gonna Give You Up', 'Shrek']
    links = []
    
    for term in search_terms:
        # Open YouTube page for each search term
        driver.get('https://www.youtube.com/results?search_query={}'.format(term))
        # Find a first webelement with video thumbnail on the page
        link_webelement = driver.find_element(By.CSS_SELECTOR, 'div#contents ytd-item-section-renderer>div#contents a#thumbnail')
        # Grab webelement's href, this is your link, and store in a list of links:
        links += [link_webelement.get_attribute('href')]
    
    print(links)
    

    希望这会有所帮助。请记住,要像这样抓取数据,您不必打开网页并使用 selenium,有像 Beautiful Soup 这样的库可以帮助您更快地完成此类事情。

    【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2020-07-23
    • 2019-06-30
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多