View difference between Paste ID: q8fw5hQa and MrBaFagS
SHOW: | | - or go back to the newest paste.
1
import urllib3
2
import os
3-
from bs4 import BeautifulSoup
3+
import time
4
from sys import exit
5-
os.system("mode con: cols=50 lines=25")
5+
6
# diretório atual
7-
url = 'http://nyaa.se'
7+
curdir = os.getcwd()
8
9
#lista de animes
10
animes = [['Coppelion',
11
           'Kill la Kill',
12-
def printalogo():
12+
           'Golden Time',
13-
	logo = ["|\    | \   /   /\       /\\", "| \   |  \ /   /  \     /  \         ___", "|  \  |   |   /____\   /____\       / _ \ |  | ", "|   \ |   |  |      | |      |  _  |  __/ |  |", "|    \|   |  |      | |      | |_|  \___| \__/"]
13+
           'Yuushibu'],
14-
	for item in logo:
14+
          ['coppelion.jpg',
15-
		print(item)
15+
           'killlakill.jpg'
16-
	print("_____________________________")
16+
           'goldentime.jpg']]
17-
	print("Python Anime Observer!\n\nV:0.2")
17+
18
#lista de fansubs
19-
printalogo()
19+
20-
print ("Status obtido: ")
20+
21-
print (r.status)
21+
22-
if (r.status == 200):
22+
           'WhyNot',
23-
	print("Iniciando conversão de bytes para UTF-8...")
23+
           'Vivid',
24-
	t = r.data.decode("utf8")
24+
           'FFF',
25-
	print("Conversão completa.")
25+
           'GotWoot',
26-
	HTML = BeautifulSoup(t)
26+
           'EveTaku',
27-
	data = str(HTML.find_all('tr',attrs={'class':'tlistrow'}))
27+
           'Coalgirls']
28-
	os.system("cls")
28+
29-
	printalogo()
29+
# conexão com a página
30-
else:
30+
31-
	os.system("cls")
31+
url = 'http://www.nyaa.se/?page=rss'
32-
	printalogo()
32+
33-
	print ("Status retornado é desconhecido (" + str(r.status) + ")")
33+
34-
	os.system("pause")
34+
35
# começo e fim da página de HTML
36-
data = t
36+
startTable = "<html><body><FONT FACE='arial'><table border=\"2\">"
37-
animes = ['Shingeki no Kyojin',
37+
endTable = "</table></FONT></body></html>"
38-
          'Gatchaman Crowds',
38+
39-
          'Inu to Hasami wa Tsukaiyou',
39+
# retorna o status obtido na conexão
40-
		  'The World God Only Knows'
40+
print("Status obtido: " + str(r.status))
41-
		  'Gin no Saji'] #TODO: tornar customizável
41+
if (r.status != 200):
42
    print("O script não será mais executado.")
43-
tags = ("<tr", "</tr>", "<td", "</td>")
43+
    os.system("pause")
44
    exit(0)
45
46
print("Iniciando conversão para UTF-8...")
47
48-
		   'WhyNot']
48+
# tenta decodificar para UTF8
49
try:
50-
ctr = []
50+
    t = r.data.decode("utf8")
51-
ftr = []
51+
except DECODEERROR as E:
52
    print("Ocorreu um erro: " + str(E))
53-
# ------------------------------------ #
53+
    print("O script será parado agora.")
54-
# Funções que pegam posições das tags  #
54+
    exit(0)
55-
# ------------------------------------ #
55+
print("Conversão completa.")
56
57-
def encontraTD(n):
57+
#passamos a info para uma variável
58-
        comeco = data.find(tags[2],n)
58+
HTML = str(r.data)
59-
        fim = data.find(tags[3],comeco)
59+
60-
        return [comeco,fim]
60+
#lista para armazenar os torrents
61
itemList = []
62-
def encontraTR(n):
62+
63-
	comeco = data.find(tags[0],n)
63+
class Item:
64-
	fim = data.find(tags[1],comeco)
64+
    def __init__(self, start, end):
65-
	ctr.append(comeco)
65+
        self.start = start
66-
	ftr.append(fim)
66+
        self.end = end
67-
	return [comeco,fim]
67+
        self.data = HTML[start+6:end]
68
        self.title = self.getTitle()
69-
# ------------------------------------------ #
69+
        self.category = self.getCat()
70-
# Percorre o arquivo inteiro.                #
70+
        self.DL = self.getDownloadLink()
71-
# Capturando primeiro os pontos de TR,       #
71+
        self.VL = self.getViewLink()
72-
# depois os TDs entre o começo e fim do TR   #
72+
        self.description = self.getDescription()
73-
# ------------------------------------------ #
73+
        self.date = self.getDate()
74
    def getTitle(self):
75-
contador = 1
75+
        a = self.data.find("<title>")
76-
lastTR = 0
76+
        b = self.data.find("</title>")
77
        return str(self.data[a+7:b])
78-
        gotTR = encontraTR(lastTR)
78+
    def getCat(self):
79-
        if gotTR[0] > 0 and gotTR[1] > 0:
79+
        me = self.data.find("<category>")
80-
                lastTD = gotTR[0]+1
80+
        ow = self.data.find("</category>")
81-
                ctd = []
81+
        return str(self.data[me+10:ow])
82-
                ftd = []
82+
    def getDownloadLink(self):
83-
                while (1):
83+
        a = self.data.find("<link>")
84-
                        gotTD = encontraTD(lastTD)
84+
        b = self.data.find("</link>")
85-
                        ctd.append(gotTD[0])
85+
        return str(self.data[a+6:b])
86-
                        ftd.append(gotTD[1])
86+
    def getViewLink(self):
87-
                        lastTD = gotTD[1]+1
87+
        a = self.data.find("<guid>")
88-
                        #print("TD " + str(contador) + ": " + str(gotTD))
88+
        b = self.data.find("</guid>")
89-
                        if lastTD+14 >= gotTR[1]:
89+
        return str(self.data[a+6:b])
90-
                                #print("\nTDs: " + str([ctd,ftd]))
90+
    def getDescription(self):
91-
                                break
91+
        a = self.data.find("<description>")
92-
                contador+=1
92+
        b = self.data.find("</description>")
93-
        lastTR = gotTR[1]+1
93+
        return str(self.data[a+22:b-3])
94-
        #print("TR: " + str(gotTR))
94+
    def getDate(self):
95-
        if gotTR[0] == -1 or gotTR[1] == -1:
95+
        a = self.data.find("<pubDate>")
96-
                break
96+
        b = self.data.find("</pubDate>")
97
        return str(self.data[a+9:b])
98-
#print("\nctr: " + str(ctr))
98+
99-
#print("ftr: " + str(ftr))
99+
# separa os itens em objetos e coloca no array itemList
100-
#print("CTRs: " + str(len(ctr)))
100+
101-
#os.system("pause")
101+
def encontraItem(n):
102
    comeco = HTML.find("<item>", n)
103-
# -------------------------------- #
103+
    fim = HTML.find("</item>", comeco)
104-
# inicia busca dentro de torrents  #
104+
    if comeco == -1 or fim == -1:
105-
# -------------------------------- #################################################
105+
        return [-1, -1]
106-
# Torrents selecionados tem seus TRs nos arrays 'foundC' (começo) e 'foundF' (fim) #
106+
    else:
107-
# -------------------------------------------------------------------------------- #
107+
        thisItem = Item(comeco,fim)
108
        itemList.append(thisItem)
109-
foundC = []
109+
        print("thisItem: " + str(thisItem.end))
110-
foundF = []
110+
        return [comeco, fim]
111
112-
encontrar = "English-translated"
112+
ultimoitem = 0
113-
#print("Procurando caracteres entre " + str(ctr[0]) + " (<tr>) e " + str(ftr[len(ftr)-1]) + " (</tr>)...")
113+
114-
for i in range(len(ctr)):
114+
115-
        busca = data.find(str(" " + encontrar),ctr[i],ftr[i])
115+
# percorrer a info que pegamos direto do site
116-
        if busca == -1:
116+
117-
                #print("Nada")
117+
118-
                i+=1
118+
    umitem = encontraItem(ultimoitem)
119-
        else:
119+
    if umitem[0] > 0 and umitem[1] > 0:
120-
                #print(busca)
120+
        ultimoitem = umitem[0]+1
121-
                foundC.append(ctr[i])
121+
        print("Começo: " + str(umitem[0]))
122-
                foundF.append(ftr[i])
122+
        print("Fim: " + str(umitem[1]))
123-
                i+=1
123+
        contador += 1
124-
                contador+=1
124+
    if umitem[0] == -1 or umitem[1] == -1:
125-
        if i == len(ctr):
125+
        print("Itens encontrados: " + str(contador))
126-
                print("\nEncontrados " + str(contador) + " torrents com \"" + encontrar + "\"")
126+
        break
127-
                break
127+
128-
#print(foundC)
128+
# separar os animes que queremos
129-
#print(len(foundC))
129+
130-
#print(foundF)
130+
animeList = []
131
contador = 0
132-
# ----------------------- #
132+
for i in range(len(itemList)):
133-
# Refina busca por fansub #
133+
    for x in range(len(animes[0])):
134-
# ----------------------- #
134+
        if itemList[i].title.find(animes[0][x]) != -1 and itemList[i].category.find("English-translated") != -1:
135
            print("Title: " + itemList[i].title)
136-
torrentsC = []
136+
            print("Anime: " + animes[0][x])
137-
torrentsF = []
137+
            animeList.append(itemList[i])
138
            contador += 1
139-
print("Procurando torrents de fansubs...")
139+
140-
for i in range(len(foundC)):
140+
print("Torrens provaveis: " + str(contador))
141-
        for x in range(len(fansubs)):
141+
142-
                busca = data.find(fansubs[x], foundC[i], foundF[i])
142+
# abrimos um arquivo para escrever o HTML 
143-
                if busca != -1:
143+
file = open(curdir + "\page.html","w",encoding="utf8")
144-
                        contador+=1
144+
HTML = startTable
145-
                        torrentsC.append(foundC[i])
145+
146-
                        torrentsF.append(foundF[i])
146+
def NewLine(string):
147
    return "<tr>" + string + "</tr>"
148-
print("Encontrados " + str(contador) + " torrents de fansubs conhecidos.")
148+
149
def NewRow(string):
150-
#print(torrentsC)
150+
    return "<td>" + string + "</td>"
151-
#print(torrentsF)
151+
152
for i in range(len(animeList)):
153-
# ------------------------------------------------------------------------ #
153+
    HTML += NewLine(NewRow(animeList[i].title) + NewRow(animeList[i].description) + NewRow(animeList[i].DL + NewRow(animeList[i].date)))
154-
# Começar a tratar os torrents individualmente, separando-os pelas tags tr #
154+
155-
# ------------------------------------------------------------------------ #
155+
HTML += endTable
156
file.write(HTML)
157-
print("Separando torrents...")
157+
file.close()