Hello i get following error:
pytube.exceptions.RegexMatchError: get_ytplayer_config: could not find match for config_patterns
My python version: 3.9.2
Can somebody please help me?
My Code:
from tkinter import ttk
from tkinter import filedialog
from pytube import YouTube #pip install pytube3
Folder_Name = ""
#file location
def openLocation():
global Folder_Name
Folder_Name = filedialog.askdirectory()
if(len(Folder_Name) > 1):
locationError.config(text=Folder_Name,fg="green")
else:
locationError.config(text="Please Choose Folder!!",fg="red")
#donwload video
def DownloadVideo():
choice = ytdchoices.get()
url = ytdEntry.get()
if(len(url)>1):
ytdError.config(text="")
yt = YouTube(url)
if(choice == choices[0]):
select = yt.streams.filter(progressive=True).first()
elif(choice == choices[1]):
select = yt.streams.filter(progressive=True,file_extension='mp4').last()
elif(choice == choices[2]):
select = yt.streams.filter(only_audio=True).first()
else:
ytdError.config(text="Paste Link again!!",fg="red")
#download function
select.download(Folder_Name)
ytdError.config(text="Download Completed!!")
root = Tk()
root.title("YTD Downloader")
root.geometry("350x400") #set window
root.columnconfigure(0,weight=1)#set all content in center.
#Ytd Link Label
ytdLabel = Label(root,text="Enter the URL of the Video",font=("jost",15))
ytdLabel.grid()
#Entry Box
ytdEntryVar = StringVar()
ytdEntry = Entry(root,width=50,textvariable=ytdEntryVar)
ytdEntry.grid()
#Error Msg
ytdError = Label(root,text="Error Msg",fg="red",font=("jost",10))
ytdError.grid()
#Asking save file label
saveLabel = Label(root,text="Save the Video File",font=("jost",15,"bold"))
saveLabel.grid()
#btn of save file
saveEntry = Button(root,width=10,bg="red",fg="white",text="Choose Path",command=openLocation)
saveEntry.grid()
#Error Msg location
locationError = Label(root,text="Error Msg of Path",fg="red",font=("jost",10))
locationError.grid()
#Download Quality
ytdQuality = Label(root,text="Select Quality",font=("jost",15))
ytdQuality.grid()
#combobox
choices = ["720p","144p","Only Audio"]
ytdchoices = ttk.Combobox(root,values=choices)
ytdchoices.grid()
#donwload btn
downloadbtn = Button(root,text="Donwload",width=10,bg="red",fg="white",command=DownloadVideo)
downloadbtn.grid()
#developer Label
developerlabel = Label(root,text="Dream Developers",font=("jost",15))
developerlabel.grid()
root.mainloop()
The error pytube.exceptions.RegexMatchError: get_ytplayer_config: could not find match for config_patterns has been a known bug in pytube. You can either update the request.py file. Or the best way is to update pytube:
python -m pip uninstall pytube pytube3 pytubex
python -m pip install git+https://github.com/nficano/pytube
Related
This question already has answers here:
python dictionary keyError
(5 answers)
Closed 11 days ago.
This post was edited and submitted for review 11 days ago and failed to reopen the post:
Original close reason(s) were not resolved
my code on line 152 is giving me KeyError. I suspect it to be an error from radar API or from the os module. API key may also be in question. Please help!
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
import tkinter as tk
from tkinter import *
import turtle
from playsound import playsound
#pip install playsound==1.2.2, pyfiglet, SpeechRecognition, PyAudio, pyttsx3,termcolor
#Wish Happy New Year 2023
import pyfiglet
import time
from termcolor import colored,cprint
wish =['Welcome','To','The','AI','Assistant']
count=0
colors=['green','yellow','magenta','cyan','orange']
playsound('C:/Users/anish/Start_up.mp3',False)
for i in range(1,6):
if(count>4):
count=0
cprint('*'*60,'red')
else:
color=colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width = 150)
cprint(msg,color)
count = count + 1
time.sleep(0.7)
# CODE FOR PROGRAM:
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
newVoiceRate = 145
engine.setProperty('rate',newVoiceRate)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
talk("Talk after the tune!")
playsound("C:/Users/anish/correct-2-46134.mp3",False)
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
print(command)
except:
pass
return command
def run_alexa():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
y = pyjokes.get_joke()
print(y)
talk(y)
elif 'shut up' in command:
LOL = "Haha, you cannot stop me! But, I will stop now. Bye!"
print(LOL)
talk(LOL)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3', False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
exit()
elif "stop" in command:
STO_P = "Ok, I will stop. Bye!"
print(STO_P)
talk(STO_P)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3',False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
time.sleep(2)
result = pyfiglet.figlet_format("Built using Python", font="digital")
print(result)
time.sleep(4)
exit()
elif "open" in command:
ope_n = command.replace("open",'')
talk('opening' + ope_n)
from AppOpener import open
open(ope_n)
elif"website" in command:
url = command.replace("website",'')
x = "Opening Website"
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open(url)
print("Okay, just a minute!")
talk(x)
elif "where is" in command:
import os
from radar import RadarClient
# initialize client
radar = RadarClient(os.environ["RADAR_SECRET_KEY"])
# get a geofence by id
geofence = radar.geofences.get(id='123')
# list geofences
radar.geofences.list()
else:
talk('Please say the command again.')
while True:
run_alexa()
I tried changing my radar api key, but not working. Also checked my code!
Maybe it is either the api key, or something wrong with the os module.
I am actually working on a small project, but as one def function controls it, had to paste the entire code.
Inconvenience regretted!
I hope we can solve this as soon as we can!
I have switched to OpenStreetMaps now, but bould still love to know about the issue, ThankYou!!!
I'm relatively new to Python and this is my first application. The code works well when run though terminal and in Pycharm but when I packaged it using Py2app and tied launching it through the file created "Paattajahaku.app" I get the message "Paattajahaku quit unexpectedly." Does anyone know whats wrong?
Thanks!
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
from time import sleep
from random import randint
root = tk.Tk()
root.title("Tkinter open file dialog")
root.resizable(False, False)
root.geometry("300x150")
titleslist = []
nameslist = []
fonrlist = []
df = pd.DataFrame(titleslist)
def select_file():
filetypes = (
("text files", "*txt",
"excel files", "*xlsx")
)
filename = fd.askopenfile(
title="open a file",
initialdir="/",
)
print("Please wait...")
for files in filename:
newfo_nr = files.strip().zfill(8)
fonrlist.append(newfo_nr)
sleep(randint(2, 4)) # sleep for a random time
url = f"https://www.asiakastieto.fi/yritykset/fi/{newfo_nr}/paattajat"
page = requests.get(url)
soup = bs(page.content, "html.parser")
names = soup.find_all(attrs={"data-title": "Nimi"})
titles = soup.find_all(attrs={"data-title": "Asema"})
for title in titles:
titleslist.append(title.text)
for name in names:
nameslist.append(name.text)
number_of_names = len(nameslist)
number_of_fo_nr = len(fonrlist)
sumfo = number_of_names - number_of_fo_nr
for i in range(sumfo):
if i < sumfo:
fonrlist.append(newfo_nr.strip())
if title == " ":
break
else:
continue
break
else:
continue
break
else:
continue
break
print("Files saved")
df = pd.DataFrame(list(zip(fonrlist, titleslist, nameslist))) # works
try:
# with block automatically closes file
with fd.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
df.to_excel(file.name)
except AttributeError:
# if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
print("The user cancelled save")
def saveFile():
try:
# with block automatically closes file
with fd.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
df.to_excel(file.name, index=False, header=False)
except AttributeError:
# if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
print("The user cancelled save")
open_button = ttk.Button(
root,
text="Open a file",
command=select_file
)
exit_button = ttk.Button(
root,
text="Exit",
command=root.destroy
)
open_button.pack(expand=True)
exit_button.pack(expand=True)
root.mainloop()
I want to get user input used in another program as a input for url and path. But thats seems to be impossible.
#mymodule.py script
from pytube import YouTube
import pytube
# import check_avail
class vdodownload:
def __init__(self,url,path):
self.url = url
self.path = path
def link(self):
try:
print(f'Downloading video: {YouTube(self.url).title}')
# yt = check_avail.video(self.url,self.path)
YouTube(self.url).streams.first().download(self.path)
print(f'Downloaded video: {YouTube(self.url).title}')
except pytube.exceptions.ExtractError:
print(f'Video {self.url} is unavaialable, skipping.')
# else:
# print(f'Downloading video: {self.url}')
# yt.streams.first().download(self.path)
# print(f'Downloaded video: {self.url}')
url = input("Enter the video URL: ")
path = input("Enter the path: ")
t = vdodownload(url,path)
t.link()
#check_avail.py script
from pytube import YouTube
if __name__ == "__main__":
def video(url,path):
y = YouTube(url)
# video1 = YouTube(url).streams.first().download(path)
# print(f"title:{YouTube(url).title}, views:{YouTube(url).views}, Length:{YouTube(url).length}")
print("Successfully done")
return video
else:
def check(func):
def parameters(u,v):
print(f"title:{YouTube(u).title}, views:{YouTube(u).views}, Length:{YouTube(u).length}")
return func(u,v)
return parameters
# return check
def filtering(func):
def param(u,v):
check1 = YouTube(u).streams.filter(type='video',progressive=True,file_extension='mp4')
print(check1)
return func(u,v)
return param
# return filtering
#filtering
#check
def video(url,path):
y = YouTube(url)
# video1 = YouTube(url).streams.first().download(path)
print("Success")
return video
url = input("Enter input url here: ")
path = input("Enter path here: ")
video(url,path)
I want to get user input from another python script named mymodule.py for check_avail.py input for url and path. I have searched online but no good answer.
can anyone help me?
After so many search I found an answer.
If you are creating a class of methods in a python program and use user-defined variables from another python script you have to create a object in that python script from where you need to import it.
<--create scrpit1.py-->
from pytube import YouTube
def video(url,path):
y = YouTube(url)
video1 = YouTube(url).streams.first().download(path)
print("Success")
return video
url = input("Enter input url here: ")
path = input("Enter path here: ")
<---- Create a object here so that you can import and use anywhere-->
t = video(url,path)
script2.py
<---Use imported variables-->
from pytube import YouTube
import pytube
# import check_avail
class vdodownload:
<-- accessing it from another script and initialise to another variable-->
def __init__(self,url,path):
self.url = t.url
self.path = t.path
<-- or you can directly use it here by giving t.url -->
def link(self):
try:
print(f'Downloading video: {YouTube(t.url).title}')
# yt = check_avail.video(t.url,t.path)
YouTube(t.url).streams.first().download(t.path)
print(f'Downloaded video: {YouTube(t.url).title}')
This is one way of doing it. Pls correct it if any changes needed.
I have installed Anaconda on my PC, and I've also added Anaconda to path. I've made a script which works fine in Jupyter, and it also works fine when I call it from the Anaconda Prompt terminal. However, when I try to execute it as a Python script from my desktop, nothing happens. I don't even get an output, so I can see what's going wrong. This is the script:
from bs4 import BeautifulSoup
import requests
import re
import urllib.request
import os
from tkinter import *
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import Tk, Menu, Canvas
import datetime
from pathlib import Path
url = requests.get("https://politiken.dk/underholdning/wulffmorgenthaler/")
html = url.text
soup = BeautifulSoup(html,'lxml')
main = soup.find_all("a", attrs={"data-prefetchable":"true"})
list_of_links = []
for i in main:
list_of_links.append(re.findall(r'(https://politiken.dk/underholdning/wulffmorgenthaler/.{1,34}(?="))', str(i))[0])
list_of_links = list(dict.fromkeys(list_of_links))
counter = 0
def next_day():
global counter
counter += 1
today = datetime.date.today()
date = today - datetime.timedelta(days=counter)
final_date = date.strftime("%m%d")
image_downloader(final_date)
def prev_day():
global counter
if counter == 0:
pass
else:
counter -= 1
today = datetime.date.today()
date = today - datetime.timedelta(days=counter)
final_date = date.strftime("%m%d")
image_downloader(final_date)
def image_downloader(date_numbers):
global counter
my_file = Path(fr"C:\Users\Peter\Desktop\Wolfmorgenthaler/{date_numbers}.jpg")
if my_file.exists():
open_img(date_numbers)
elif counter<len(list_of_links):
new_url = requests.get(list_of_links[counter])
new_html = new_url.text
new_soup = BeautifulSoup(new_html,'html')
new_main = new_soup.find_all("img", attrs={"class":"media__image image--fullwidth"})
new_picture_links = re.findall(r'https.+? ', str(new_main[0]))
final_link = new_picture_links[0]
fullfilename = os.path.join(r"C:\Users\Peter\Desktop\Wolfmorgenthaler", f"{date_numbers}.jpg")
urllib.request.urlretrieve(final_link, fullfilename)
open_img(date_numbers)
else:
counter = counter - 1
def open_img(name):
filepath = fr"C:\Users\Peter\Desktop\Wolfmorgenthaler/{name}.jpg"
img = Image.open(filepath)
img = img.resize((960, 449), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.grid(row = 1, columnspan=4)
root = Tk()
root.geometry("964x483")
root.resizable(width=True, height=True)
today = datetime.date.today()
date = today - datetime.timedelta(days=counter)
final_date = date.strftime("%m%d")
image_downloader(final_date)
btn1 = Button(root, text='Næste billede', command=next_day, width = 67).grid(row = 2, column = 2)
btn2 = Button(root, text='Forrige billede', command=prev_day, width = 67).grid(row = 2, column = 1)
root.mainloop()
I just reset my PC today, and it worked just fine before I reset it. I have no idea how to get it to work. I would like to just have it be a clickable icon on my desktop, which executes the script.
Executing it with a batch file did not work either. Any ideas?
This is the weirdest solution found here:
Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website
" My workaround: I have copied the following files
libcrypto-1_1-x64.*
libssl-1_1-x64.*
from D:\Anaconda3\Library\bin to D:\Anaconda3\DLLs.
And it works as a charm! "
I had made a youtube video downloader using pytube in python. It previously works fine but during sometime it gives an error of "assets". I had tried a lot but I can't solve it. I had also tried to search error solution but I can't found anything like that.
Here is my code
def startDownload(url):
global file_size
path_to_save = askdirectory()
if path_to_save is None:
return
try:
global MaxFileSize, fileSizeInBytes
choice = youtubeChoicesLabel.get()
url=urlField.get()
yt = YouTube(url)
nome = yt.title
if (choice == download_choices[1]):
print("720p video is downloading")
selectVideo = yt.streams.filter(progressive=True, file_extension='mp4').first()
elif (choice == download_choices[2]):
print("144 video is downloading")
selectVideo = yt.streams.filter(progressive=True, file_extension='mp4').last()
selectVideo = yt.streams.filter(only_audio=True).first()
elif (choice == download_choices[0]):
return
fileSizeInBytes = selectVideo.filesize
MaxFileSize = fileSizeInBytes/1024000
MB =str(MaxFileSize)+ "MB"
print("File Size = : {:00.000f}".format (MaxFileSize))
st= selectVideo
yt.register_on_complete_callback(complete_download)
yt.register_on_progress_callback(progress_download)
file_size=st.filesize
st.download(output_path=path_to_save)
except Exception as e:
print(e)
download_choices = ["----Download Type----",
"Mp4 720p",
"Mp4 144p",
# "Video 3gp",
"Audio Mp3"]
def btnClicked():
try:
downloadBtn['text'] = "Please wait....."
downloadBtn["bg"] = "red"
downloadBtn["fg"] ="white"
downloadBtn['state']= 'disabled'
url=urlField.get()
if url == '':
showinfo("Message","Please input a url of the video.....")
return
print(url)
thread= Thread(target=startDownload,args=(url,))
thread.start()
except Exception as e:
print(e)
Here is my error
soham#LAPTOP-FJLV55TK MINGW64 ~
y"python "e:/python projects/YOUTUBE VIDEO DOWNLOADER/YOUTUBE_VIDEO_DOWNLOADER.py
e:/python projects/YOUTUBE VIDEO DOWNLOADER/YOUTUBE_VIDEO_DOWNLOADER.py
https://www.youtube.com/watch?v=rTuxUAuJRyY
'assets'
I had the same problem and updating pytube to the latest version available currently the problem disappeared.
pip install pytube==10.0.0
or
pip install --upgrade pytube
Similar question.