Skip to content

Instantly share code, notes, and snippets.

@NrI3
Created June 14, 2022 13:21
Show Gist options
  • Save NrI3/bfc2ebd4ce7ef33f420ca8d4732d406e to your computer and use it in GitHub Desktop.
Save NrI3/bfc2ebd4ce7ef33f420ca8d4732d406e to your computer and use it in GitHub Desktop.
Download file by extension
import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import unquote as udecode
from tqdm import tqdm
import os
from argparse import ArgumentParser
class Download:
def __init__(self):
self.url = None
self.directory = os.getcwd()+'\\'
self.extension = 'mp4'
def getHtmlFromUrl(self, url):
r = requests.get(url)
return bs(r.text,"html.parser")
def getLinks(self, html):
return html.findAll("a")
def getLinksExtensions(self, ext, links):
t = []
for l in links:
if ext in l['href']:
# fix url
if not 'http' in l['href']:
l['href'] = udecode(self.url + l['href'])
l['downloaded']=0
t.append(l)
return t
def download(self, url):
file_name = udecode(url.split("/")[-1])
response_file = requests.get(url, stream=True)
response_bytes = int(response_file.headers.get('content-length', 0))
with open(self.directory+file_name, "wb") as hfile:
with tqdm(
unit='B',
unit_scale=True,
unit_divisor=1024,
miniters=1,
desc=file_name,
total=response_bytes
) as pbar:
for chunk in response_file.iter_content(chunk_size=4096):
hfile.write(chunk)
pbar.update(len(chunk))
def download_links_extensions(self):
html = self.getHtmlFromUrl(self.url)
links = self.getLinks(html)
links = self.getLinksExtensions(self.extension,links)
for l in links:
self.download(l['href'])
if __name__ == '__main__':
parser = ArgumentParser()
down = Download()
try:
parser.add_argument("-u", help="Target Url")
parser.add_argument("-d", required=False, help="Output directory")
parser.add_argument("-t", required=False, help="Extension File")
args = parser.parse_args()
if args.u:
down.url = udecode(args.u)
print("\n\nUrl: ", down.url)
if args.t:
down.extension = args.t
print("Extension: ", down.extension)
print("Directory:", down.directory)
down.download_links_extensions()
except Exception as ex:
print(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment