~claudiotorcato/+junk/decken

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from BeautifulSoup import BeautifulSoup as bs

import urllib2
import csv
import collections
import sqlite3
import re

#c.execute("create table card (nome text, sigla text, tipo text, mana text, raridade text)")
conn = sqlite3.connect('database.db')

c = conn.cursor()

c.execute("select sigla, total from colecao")
colecoes = c.fetchall()
#print colecoes
localizadas = []
for i in colecoes:
	c.execute("select count(*) from card where sigla = ?", [ i[0] ])
	total = c.fetchone()
	if int( i[1] ) <> int(total[0] ):
		print i[1], total[0]
		localizadas.append( i[0] )
		
print len(localizadas), 'colecoes para pesquisar'

for sigla in localizadas:
	c.execute("select numero from card where sigla = ? ", [ sigla ])
	cards_existentes = []
	for card in c.fetchall():
		cards_existentes.append( card[0])
	conjunto_existents = set(cards_existentes)
	c.execute("select total, descricao from colecao where sigla = ? ", [sigla])
	resposta = c.fetchone()
	total, colecao = resposta
	total = int(total)
	conjunto_total = set( map( str, range(1, total + 1)) )
	conjunto_busca = conjunto_total - conjunto_existents
	print conjunto_existents
	print conjunto_busca
	for numero in conjunto_busca:
		print "http://www.magiccards.info/%s/en/%s.html" % (sigla, numero)
		page = urllib2.urlopen("http://www.magiccards.info/%s/en/%s.html" % (sigla, numero))
		texto = page.read()
		page.close()
		soup = bs(texto)
		nome = soup.find('a',href="/%s/en/%s.html" % (sigla, numero)).contents[0]
		ctext = soup.find('p',{'class':'ctext'})
		tipo_e_mana = ctext.previousSibling.previousSibling.contents[0]
		print tipo_e_mana
		try:
			tipo, mana = tipo_e_mana.split(',')
			mana.replace('\n','')
			mana = mana.split()[0]
		except ValueError:
			tipo, mana = tipo_e_mana, ''
		print colecao
		b = soup.findAll('b',text=re.compile(colecao))
		print b
		encontrou = False
		contador = 1
		while not encontrou:
			try:
				raridade = b[-contador]			
				raridade = raridade[ raridade.index('(') + 1 : raridade.index(')') ]
				encontrou = True
			except IndexError:
				raridade = b
				encontrou = True
			except ValueError:
				contador += 1
		try:
			texto_da_carta = ctext.contents[0].contents[0]
		except IndexError:
			texto_da_carta = ""
		tupla = nome, sigla, numero, tipo, mana, raridade, texto_da_carta
		print tupla
		if u"Missing!" in unicode(tupla[3]):
			tupla = nome, sigla, numero, '', mana, raridade, texto_da_carta
		print 'cadastrando'
		c.execute("insert into card (nome, sigla, numero, tipo, mana, raridade, texto) values (?,?,?,?,?,?,?)", tupla)
		conn.commit()
c.close()