You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3使用pytube触发RegexMatchError正则匹配失败问题

问题根因

if key in act_key判断本身没有任何问题,你只是被时序巧合误导了。报错核心原因是传入YouTube()构造函数的参数不是合法的YouTube视频链接:从你贴的运行日志可以看到,输入激活码后,premium_user函数内的input("Enter The Link ")没有阻塞等待你输入新的视频链接,直接读取到了空字符串或者输入缓冲区残留的无效换行内容,pytube无法从无效内容里匹配到规则要求的11位视频ID,才抛出正则匹配错误。

你之前测试直接给key赋固定值时代码能正常运行,是因为跳过了激活码输入+拉起浏览器的步骤,没有触发控制台输入流异常,和in判断的逻辑没有任何关系。

触发逻辑
  1. 密钥校验通过前你调用了webbrowser.get(chrome).open()拉起Chrome浏览器,在PyCharm内置控制台环境下,拉起外部GUI程序时很容易干扰标准输入流,导致后续第一个input()调用直接读取缓冲区残留的换行符,不会等待用户实际输入。
  2. 代码没有做输入合法性校验:premium_user函数拿到任意输入内容都会直接传给YouTube()构造函数,空值、无效链接自然会触发正则报错。
  3. 隐藏的逻辑bug:当用户输入的链接不含http字段时,你写的while True: download()会无限递归调用自身,运行几次就会触发栈溢出。
修复方案
  • 所有input()返回的内容统一加.strip()处理,清除首尾残留的换行、空格字符。
  • 给视频链接输入加循环校验,拿到符合格式的YouTube链接之后再初始化YouTube对象,不要直接透传原始输入内容。
  • 移除错误的递归逻辑,链接输入无效时用循环提示用户重新输入,不要递归调用download()函数。
  • 拉起浏览器后加100-200ms的短暂延时,规避PyCharm控制台的输入流干扰问题;也可以直接用系统原生cmd/终端运行脚本,不依赖PyCharm内置控制台。
修复后参考代码

main.py

from pytube import YouTube
import os
import webbrowser
import time
from act_key import act_key

chrome = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"  %s'

def is_valid_youtube_url(url: str) -> bool:
    return url.startswith(("https://www.youtube.com/watch", "https://youtu.be/")) and len(url) > 20

def premium_user():
    while True:
        link = input("Enter The Link ").strip()
        if is_valid_youtube_url(link):
            break
        print("Enter A valid Link ")
    print("Wait....")
    yt = YouTube(link)
    stream = yt.streams.get_highest_resolution()
    stream.download()
    print("Download Has Been Completed Successfully")


def download():
    allfiles = os.listdir('C:\\Users\\Abdelrhman Ayman\\PycharmProjects\\Youtube Video downloader')
    files = [fname for fname in allfiles if fname.endswith('.mp4')]
    number = len(files)
    while True:
        link = input("Enter The Link ").strip()
        if 'http' in link:
            print("Wait....")
            break
        print('Enter A valid Link ')
    if number >= 5:
        print("Subscribe Please For This Service")
        webbrowser.get(chrome).open('http://localhost:63342/Youtube%20Video%20downloader/Payment.html')
        time.sleep(0.2)
        while True:
            key = input("Enter The Activation Key ").strip()
            if key in act_key:
                premium_user()
                break
            else:
                print("This Is Not A Valid Key")
    else:
        yt = YouTube(link)
        stream = yt.streams.get_highest_resolution()
        stream.download()
        print("You Can Download ", (4 - number), " More Times")
        print("Download Has Been Completed Successfully")


if __name__ == "__main__":
    while True:
        download()

act_key.py

原有代码无需修改。

内容的提问来源于stack exchange,提问作者M4 Abdo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 22:27:32