【问题标题】:Convert YouTube link into an embed link将 YouTube 链接转换为嵌入链接
【发布时间】:2015-04-21 20:00:23
【问题描述】:

我正在使用 Python 和 Flask,并且我需要将一些 YouTube URL 转换为它们的嵌入版本。例如,这个:

https://www.youtube.com/watch?v=X3iFhLdWjqc

必须转换成这个:

https://www.youtube.com/embed/X3iFhLdWjqc

我应该使用正则表达式,还是有 Flask 方法来转换 URL?

【问题讨论】:

  • 你可以使用正则表达式或urlparse 来实现它,但我认为 Flask 不知道该怎么做
  • 非常感谢!我不知道 Python 可以做到这一点。真的谢谢!

标签: python regex flask


【解决方案1】:

你可以试试这个:

import re

videoUrl = "https://www.youtube.com/watch?v=X3iFhLdWjqc" 
embedUrl = re.sub(r"(?ism).*?=(.*?)$", r"https://www.youtube.com/embed/\1", videoUrl )
print (embedUrl)

输出:

https://www.youtube.com/embed/X3iFhLdWjqc

Demo

【讨论】:

  • URL 中的多个参数可能是个问题。
  • 同意,但 OP 没有提到这一点。
【解决方案2】:

有两种类型的 youtube 链接:

http://www.youtube.com/watch?v=xxxxxxxxxxx

http://youtu.be/xxxxxxxxxxx

使用此功能,它将与 2 种 youtube 链接一起使用。

import re
def embed_url(video_url):
        regex = r"(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)"

        return re.sub(regex, r"https://www.youtube.com/embed/\1",video_url)

【讨论】:

    【解决方案3】:

    假设您的网址只是字符串,您不需要正则表达式或特殊的 Flask 函数来执行此操作。
    此代码将根据您所说的处理方式将所有 YouTube 网址替换为嵌入式版本:

    url = "https://youtube.com/watch?v=TESTURLNOTTOBEUSED"
    url = url.replace("watch?v=", "embed/")
    

    您所要做的就是将 url 替换为您存储 URL 的任何变量。
    要对列表执行此操作,请使用:

    new_url_list = list()
    for address in old_url_list:
        new_address = address.replace("watch?v=", "embed/")
        new_url_list.append(new_address)
    
    old_url_list = new_url_list
    

    其中old_url_list 是您的网址所在的列表。

    【讨论】:

    • 谢谢!这完美地工作。它不是一个字符串,但我必须将它转换成一个。
    • @Yelp 没问题。乐意效劳。 :D
    猜你喜欢
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2022-07-31
    相关资源
    最近更新 更多