Last active
August 29, 2015 14:16
-
-
Save felipsmartins/e11589225c5150d74d58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#coding: utf-8 | |
"""Captura os links de download direto do portal hyuugadownloads.com.br. | |
$ hyuuga.py --help | |
""" | |
import sys | |
import os | |
import tempfile | |
import argparse | |
import urllib2 | |
from urllib import urlencode | |
# lxml (libxml) está instalado? | |
try: | |
from lxml import etree | |
import lxml.html | |
except ImportError: | |
print 'A pacote "lxml" não está instalado.\nVá para {}'.format( | |
"http://lxml.de/installation.html") | |
sys.exit() | |
__author__ = "Kazumi (Felipe Martins) - https://github.com/felipsmartins" | |
__maintainer__ = "Kazumi" | |
__version__ ="1.0.1" | |
__date__ = "Mar 2015" | |
MAIN_URL = "http://www.hyuugadownloads.com.br" | |
FILENAME_CACHE = os.path.join(tempfile.gettempdir(), "hyuuga.html") | |
parser = argparse.ArgumentParser(description=__doc__, version=__version__) | |
parser.add_argument("url", help="O link principal do anime") | |
parser.add_argument("sharing_server", type=int, help="""O servidor de compartilhamento (Drive, Mega, etc). | |
Um número referente a ordem disposta no site deve ser provido""") | |
parser.add_argument("-m", "--most-recent", dest="most_recent", action="store_true", default=False, | |
help="Usa o conteúdo anteriormente baixado, se existir") | |
# Isso é necessário porque o site usa paginação de resultados | |
parser.add_argument("-p", "--page", dest="page", action="store", default=1, | |
help="A página da qual deve se baixar os links de episódios. Por padrão é 1") | |
parser.add_argument("-i", "--interactive", dest="interactive", action="store_true", default=False, | |
help="Para cada episódio, pergunta se deseja-se obter o link direto para download") | |
def get_main_links(source, sharing_server): | |
"""Analisa o conteúdo HTML e catura os links principais (protetores de link) | |
Args: | |
source (str): URL ou path de arquivo | |
sharing_server (int): O número do servidor de compartilhamento. | |
Isso é baseado na ordem que está no site | |
Returns: | |
list: Uma lista de tuplas | |
""" | |
dom = lxml.html.parse(source) | |
xpatheval = etree.XPathDocumentEvaluator(dom) | |
nodes = xpatheval('//*[@id="inner-lista"]/div[@class="episodio"]') | |
# quando não encontra episódios | |
if not nodes: | |
return 0 | |
ep_titles, ep_links = [], [] | |
sharing_server_index = (sharing_server - 1) | |
for node in nodes: | |
# títulos | |
info = node.xpath('div[@class="infos"]/a/strong')[0].text | |
ep_titles.append(info.strip().encode("utf-8")) | |
# links | |
link = node.xpath('div[@class="caixa_mirror"]/table/tbody/tr') | |
link = link[sharing_server_index].find("td/a").get("href") # path link do protetor | |
ep_links.append("{url}/{path}".format(url=MAIN_URL, path=link)) | |
return zip(ep_titles, ep_links) | |
def get_download_link(link_protector): | |
""" Captura o real link protegido | |
Args: | |
link_protector (str): Uma URL | |
Returns: | |
str: O link direto para download | |
""" | |
content = get_request_content(link_protector) | |
dom = lxml.html.parse(link_protector) | |
xpatheval = etree.XPathDocumentEvaluator(dom) | |
# A estrutura dessa página é simples, só precisamos capturar o link com id=link | |
nodes = xpatheval('//body/a[@id="link"]') | |
if nodes: | |
return nodes[0].get("href") | |
def get_request_content(url, data=None): | |
"""GET/POST - Faz uma requisição HTTP retornando o resultado | |
Args: | |
url (str): URL | |
data (dict): Um dicionários de dados para | |
requisições POST | |
Returns: | |
str: O conteúdo da página requisitada | |
""" | |
if data: | |
data = urlencode(data) | |
request = urllib2.Request(args.url, data) | |
response = urllib2.urlopen(request) | |
return response.read() | |
def main(): | |
main_links = get_main_links(FILENAME_CACHE, args.sharing_server) | |
# porque o html do site pode ter mudado | |
if not main_links: | |
print "links não encontrados" | |
sys.exit() | |
for title, link in main_links: | |
if args.interactive: | |
res = raw_input("\nObter link para [{}]? (s/n)\n".format(title)) | |
if "n" == res.lower(): | |
continue # pula para o próximo link se a resposta for "não" | |
print "Buscando link para {} ...".format(title) | |
print get_download_link(link) | |
# ==================================================== | |
# Execução | |
# ==================================================== | |
if "__main__" == __name__: | |
args = parser.parse_args() | |
data = {"p": args.page} # por padrão é 1 | |
if not args.most_recent: | |
response_content = get_request_content(args.url, data) | |
#salva | |
with open(FILENAME_CACHE, "w+") as f: | |
f.write(response_content) # fazemos cache do resultado | |
# execute | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment