Advertisement
clesiomatias

pokemon_Daniel

Apr 22nd, 2022 (edited)
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.05 KB | None | 0 0
  1. import json
  2. import os
  3. import requests
  4. from bs4 import BeautifulSoup
  5.  
  6. def dados_pokemon(poke_name):
  7.     """Função que faz uma raspagem no site pokemn.db e devolve
  8.        os dados do pokemon passado como parametro"""
  9.  
  10.     #Raspagem
  11.     url = f'https://pokemondb.net/pokedex/{poke_name}'
  12.     urlEgg = f'https://pokemondb.net/pokedex/{poke_name}/egg'
  13.     urlDescription = f'https://www.pokemon.com/br/pokedex/{poke_name}'
  14.     site = requests.get(url)
  15.     egg=requests.get(urlEgg)
  16.     desc = requests.get(urlDescription)
  17.     soup = BeautifulSoup(site.content,'html.parser')
  18.     soup2 = BeautifulSoup(egg.content,'html.parser')
  19.     soup3 = BeautifulSoup(desc.content, 'html.parser')
  20.    
  21.     hps = soup.find_all('table', class_ ='vitals-table')
  22.     hps2 = soup.find_all('a', class_ ='type-icon') #tipo
  23.     hps3 = soup.find_all('span', class_ ='infocard-lg-data text-muted') #evolution
  24.     hps4 = soup.find_all('span', class_ ='infocard infocard-arrow') #requiredLevel
  25.     hps5 = soup3.find_all('div', class_='version-descriptions')
  26.     poke_description =''
  27.     for i in range(len(hps5)):
  28.         poke_description+=hps5[i].get_text().replace('\n','')
  29.         poke_description = poke_description.replace('    ','').strip()
  30.    
  31.     #------------------------------------------------------------------------------
  32.     #resolvendo o caso da evolução
  33.     evolve=''
  34.     lastEvolve = hps3[len(hps3)-1].get_text().split()[1].lower()
  35.     atualEvolve = poke_name
  36.     crawledEvolve =hps3[1].get_text().split()[1].lower()
  37.     if lastEvolve in atualEvolve:
  38.         evolve = 'This is the last evolution'
  39.     elif crawledEvolve in atualEvolve:
  40.         evolve = lastEvolve.upper()
  41.     else:
  42.         evolve = crawledEvolve.upper()
  43.  
  44.     #-----------------------------------------
  45.     #Raspagem para os egg moves
  46.     hps5 = soup2.find('nav', class_='panel panel-nav')
  47.     lista_eggs = hps5.findChildren()
  48.     egg_move_list = []
  49.     for i in lista_eggs:
  50.         if i.get_text() not in 'Egg moves' and '\n' not in i.get_text():
  51.             if i.get_text() not in egg_move_list:
  52.                 egg_move_list.append(i.get_text())
  53.    
  54.    
  55.    
  56.     #Aqui acabamos de encontrar os egg moves
  57.    
  58. #--------------------------------------------------------------------------------------
  59.     # daqui pra baixo faço acesso a uma api para conseguir os dados de moveset mais facil
  60.     poke = 'charmander'
  61.     url =f'https://pokeapi.co/api/v2/pokemon/{poke_name}'
  62.     cha = requests.get(url).text
  63.     dados = json.loads(cha)
  64.     move_list = []
  65.     for i in range (len(dados['moves'])):
  66.         name = dados['moves'][i]['move']['name']
  67.         required_level = int(dados['moves'][i]['version_group_details'][0]['level_learned_at'])
  68.         if required_level==0:
  69.             continue
  70.         else:
  71.             move_list.append(name)
  72.             move_list.append(required_level)
  73.  
  74.             #Aqui acabamos de encontrar o moveset
  75. #--------------------------------------------------------------------------------------
  76.    
  77.    
  78.     #transposição dos dados para uma lista
  79.     full_text=[]
  80.     for i in range(len(hps)):
  81.         if hps[i].get_text()!='\n':
  82.             full_text.append(f'{hps[i].get_text()}\n')
  83.  
  84.     #Criação do dicionario que será retornado com os dados
  85.     data = {
  86.         'NOME':poke_name.upper(),
  87.         'HP':'',
  88.         'ATK':'',
  89.         'DEF':'',
  90.         'SPEED':'',
  91.         'SP.ATK' :'',
  92.         'SP.DEF':'',
  93.         'EXPERIENCE':'',
  94.         'EVOLVE': evolve,
  95.         'TIPO':hps2[0].get_text().upper(),
  96.         'CHANCE':'',
  97.         'REQUIREDLEVELEVOLVE':required_level,
  98.         'MOVESSET':move_list,
  99.         'EGGMOVES':  egg_move_list if len(egg_move_list)!=0  else f'{poke_name.upper()} does not have any egg moves.',
  100.         'DESCRIPTION':poke_description
  101.         }
  102.    
  103.    
  104.    
  105.     try:
  106.         data['REQUIREDLEVELEVOLVE']=int(hps4[0].get_text().replace(')',' ').split()[1])
  107.     except:
  108.         text_level= hps4[0].get_text().replace('(','').replace(')','')  
  109.         if 'stone'in text_level.lower() :
  110.             data['REQUIRED_ITEM'] = f'ITEM.{text_level.split()[1].upper()}_{text_level.split()[2].upper()}'
  111.             data['REQUIREDLEVELEVOLVE'] = 1
  112.         else:
  113.             text_level = hps4[1].get_text().replace('(','').replace(')','')
  114.             if 'stone'in text_level.lower() :
  115.                 data['REQUIRED_ITEM'] = f'ITEM.{text_level.split()[1].upper()}_{text_level.split()[2].upper()}'
  116.                 data['REQUIREDLEVELEVOLVE'] = 1
  117.             else:
  118.                 data['REQUIREDLEVELEVOLVE']=0
  119.            
  120.        
  121.     #separando os dados brutos num arquivo de texto
  122.     for i in range(len(full_text)):
  123.         if i ==1 or i==3:  
  124.             with open(f'bruto{i}.txt','w')as bruto:
  125.                 bruto.writelines(full_text[i])
  126.            
  127.     with open('bruto3.txt','r')as bruto:
  128.         b= bruto.readlines()
  129.         #Filtrando os dados necessários e passando para o dicionario
  130.         for i in range(len(b)):
  131.             if "HP" in b[i]  :
  132.                 data['HP']=int(b[i+1])
  133.             elif "Attack" in b[i]  :
  134.                 data['ATK']=int(b[i+1])
  135.             elif "Defense" in b[i]  :
  136.                 data['DEF']=int(b[i+1])
  137.             elif "Sp. Atk" in b[i]  :
  138.                 data['SP.ATK']=int(b[i+1])
  139.             elif "Sp. Def" in b[i]  :
  140.                 data['SP.DEF']=int(b[i+1])
  141.             elif "Speed" in b[i]  :
  142.                 data['SPEED']=int(b[i+1])
  143.     with open('bruto1.txt','r')as bruto:
  144.         b= bruto.readlines()
  145.         for i in range(len(b)):
  146.             if 'Base Exp.'in b[i]:
  147.                 data['EXPERIENCE'] = int(b[i+1])
  148.             elif 'Catch rate' in b[i]  :
  149.                 data['CHANCE'] = int(b[i+2][:3])
  150.  
  151.    
  152.  
  153.     #retornando o dicionario                
  154.     return data
  155.  
  156. pokemons = [
  157.     'pikachu',
  158.     'charmander',
  159.     'bulbasaur',
  160.     'ivysaur',
  161.     'blastoise',
  162.     'metapod',
  163.     'ekans',
  164.     'vulpix'
  165.     ]
  166.  
  167. #vamos passar um laço 'for' para printar os dados de cada um:
  168. for i in pokemons:
  169.     print(f'{dados_pokemon(i)}\n\n\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement