import urllib.request, re, os, time, requests

    
ab = ["AK", "WA", "OR", "CA", "HI", "ID", "NV", "UT", "AZ", "MT", "WY", "CO", "NM", "ND", "SD", "NE", "KS", "OK", "TX",
     "MN", "IA", "MO", "AR", "LA", "IL", "IN", "KY", "TN", "MS", "WI", "OH", "WV", "NC", "AL", "MI", "PA", "VA", "SC", "GA",
     "NY", "NJ", "MD", "DC", "FL", "VT", "MA", "CT", "DE", "ME", "NH", "RI", "RI"]
g = 0
while g < 1 :
    liste_state = []
    pourcent_HC = []
    grandsE_HC = []
    votes_HC = []
    pourcent_DT = []
    grandsE_DT = []
    votes_DT = []
    list_est = []
    
    for a in ab :
    
        file = urllib.request.urlopen('http://data.cnn.com/ELECTION/2016/'+a+'/state/'+a+'.json')
    
    
        for b in file :
            b = b.decode('UTF-8')
            state = b.split('{"bgs":false,"state":"')
            state = state[1].split('","code"')
            liste_state.append(state[0])
            
            est = b.split('"pctsrep":')
            est = est[1].split(',"sw":')
            list_est.append(est[0])
        
        
            #HC
        
            votesHC = b.split('{"id":1746,"fname":"Hillary"')
            PCHC = votesHC[1].split('"pctDecimal":"')
            PCHC = PCHC[1].split('","inc"')
            pourcent_HC.append(PCHC[0])
        
            GE_HC = votesHC[1].split('evotes":')
            GE_HC = GE_HC[1].split("}")
            grandsE_HC.append(GE_HC[0])
        
            votesHC = votesHC[1].split('"votes":')
            votesHC = votesHC[1].split(',"cvotes"')
            votes_HC.append(votesHC[0])
        
            #DT
            votesDT = b.split('{"id":8639,"fname":"Donald"')
            PCDT = votesDT[1].split('"pctDecimal":"')
            PCDT = PCDT[1].split('","inc"')
            pourcent_DT.append(PCDT[0])
        
            GE_DT = votesDT[1].split('evotes":')
            GE_DT = GE_DT[1].split("}")
            grandsE_DT.append(GE_DT[0])
        
            votesDT = votesDT[1].split('"votes":')
            votesDT = votesDT[1].split(',"cvotes"')
            votes_DT.append(votesDT[0])
    p=0
    liste_fr = []
    while p < len(ab)-1 :
    
        if liste_state[p] == "New Mexico" : liste_fr.append("Novo México")
        elif liste_state[p] == "California" : liste_fr.append("Califórnia")
        elif liste_state[p] == "New York" : liste_fr.append("Nova Iorque")    
        elif liste_state[p] == "North Dakota" : liste_fr.append("Dakota do Norte")    
        elif liste_state[p] == "South Dakota" : liste_fr.append("Dakota do Sul")
        elif liste_state[p] == "New Hampshire" : liste_fr.append("Nova Hampshire")
        elif liste_state[p] == "West Virginia" : liste_fr.append("Virgínia Ocidental")
        elif liste_state[p] == "North Carolina" : liste_fr.append("Carolina do Norte")
        elif liste_state[p] == "South Carolina" : liste_fr.append("Carolina do Sul")
        elif liste_state[p] == "Pennsylvania" : liste_fr.append("Pensilvânia")
        elif liste_state[p] == "Virginia" : liste_fr.append("Virgínia")
        elif liste_state[p] == "Georgia" : liste_fr.append("Geórgia")
        elif liste_state[p] == "Dist. of Columbia" : 
            liste_state[p] = "District of Columbia" 
            liste_fr.append("Distrito de Colúmbia")
        elif liste_state[p] == "Florida" : liste_fr.append("Flórida")
        elif liste_state[p] == "New Jersey" : liste_fr.append("Nova Jersey")
        elif liste_state[p] == "Hawaii" : liste_fr.append("Havaí")
        else : liste_fr.append(liste_state[p])
    
        p = p + 1
    
    
    p = 0
    while p < len(ab)-1 :
    
        print('Etat : ',liste_state[p] )
        print(list_est[p], '%' )
        
        #print('HC, votes :', votes_HC[p], 'pourcentage : ', pourcent_HC[p],' grands électeurs : ', grandsE_HC[p])
        #print('DT, votes :', votes_DT[p], 'pourcentage : ', pourcent_DT[p],' grands électeurs : ', grandsE_DT[p])
    
    
    
        contenu = "{{evento atual}}"+"\n"+"{{Infotabela Estados Unidos}}"
        contenu = contenu+'<div style="border: none; text-align:left; background-color:#F6F6F6; border-top:1px solid #A7D7F9; border-bottom:1px solid #A7D7F9;">&nbsp;</span><span style="padding-left:2px;">[[Imagem:Nuvola apps backward arrow.svg|15px|link=Eleição Presidencial nos Estados Unidos em 2016: a noite da eleição]] <b>[[Eleição Presidencial nos Estados Unidos em 2016: a noite da eleição|Retornar para o mapa dos resultados]]</b></span><span style="font-size:4px;">&nbsp;</span></div>'
        contenu = contenu+"\n"+"{{data|9 de novembro de 2016}} '''Resultados ("+list_est[p]+" %), actualizados em ~~~~~ '''"+"\n"
        contenu = contenu+"\n"+"\n"+'{{Subst:Utilizador:Mattho69/Test|état='+liste_fr[p]+'|état en='+liste_state[p]+'|votes HC='+votes_HC[p]
        contenu = contenu+'|votes HC='+votes_HC[p]+'|pourcent HC='+pourcent_HC[p]+'|GE HC='+grandsE_HC[p]
        contenu = contenu+'|votes DT='+votes_DT[p]+'|pourcent DT='+pourcent_DT[p]+'|GE DT='+grandsE_DT[p]+'}}'+"\n"+"\n"+"\n"
    
        contenu =contenu+"\n" 
        contenu =contenu+'== Fonte =='+"\n"
        contenu =contenu+'*{{fonte| idioma = en'+"\n"
        contenu =contenu+'| título ='+str.lower(liste_state[p])+' presidential results'+"\n"
        lien =  str.lower(liste_state[p]).replace(" ","-")
        contenu =contenu+'| url = http://edition.cnn.com/election/results/states/'+lien+'/president'+"\n"
        contenu =contenu+'| autor  = cnn.com | pub    = CNN'+"\n"
        contenu =contenu+'| data   = 8 de Novembro de 2016 (início da apuração)}}'+"\n"+"\n"+"\n"
    
        contenu = contenu+'{{mídias sociais}}'+"\n"
        #contenu = contenu+'{{Page États-Unis}}'+"\n"
    
        contenu = contenu+'[[Categoria:Política]]'+"\n"+'[[Categoria:Eleições]]'+"\n"+'[[Categoria:Política nos Estados Unidos]]'+"\n"
        contenu = contenu+'[[Categoria:Eleições 2016]]'+"\n"+'[[Categoria:Eleição Presidencial nos Estados Unidos em 2016]]'+"\n"
        contenu = contenu+'[[Categoria:Donald Trump]]'+"\n"+'[[Categoria:Hillary Clinton]]'+"\n"
        contenu = contenu+'[[Categoria:'+liste_fr[p]+']]'

    
    
        username = 'Mattho69'
        password = ''
        baseurl = 'https://pt.wikinews.org/w/'
        summary = '[Bot] Eleição US 2016'
        message = contenu
        #sectiontitle = liste_state[p]
        
        title = 'Eleição Presidencial nos Estados Unidos em 2016: '+liste_fr[p]
        
        
        # Login request
        payload = {'action': 'query', 'format': 'json', 'utf8': '', 'meta': 'tokens', 'type': 'login'}
        r1 = requests.post(baseurl + 'api.php', data=payload)

        # login confirm
        login_token = r1.json()['query']['tokens']['logintoken']
        payload = {'action': 'login', 'format': 'json', 'utf8': '', 'lgname': username, 'lgpassword': password, 'lgtoken': login_token}
        r2 = requests.post(baseurl + 'api.php', data=payload, cookies=r1.cookies)
        
        # get edit token2
        params3 = '?format=json&action=query&meta=tokens&continue='
        r3 = requests.get(baseurl + 'api.php' + params3, cookies=r2.cookies)
        edit_token = r3.json()['query']['tokens']['csrftoken']

        
        edit_cookie = r2.cookies.copy()
        edit_cookie.update(r3.cookies)

        if votes_HC[p] != "0" :
            # save action
            payload = {'action': 'edit', 'assert': 'user', 'format': 'json',  'utf8': '', 'text': message,'summary': summary, 'title': title, 'token': edit_token}
            r4 = requests.post(baseurl + 'api.php', data=payload, cookies=edit_cookie)
            
            print("ECRIT")
            time.sleep(10)
        p = p + 1
        
    time.sleep(10800)
Etat :  Alaska
76 %
ECRIT
Etat :  Washington
94 %
ECRIT
Etat :  Oregon
87 %
ECRIT
Etat :  California
83 %
ECRIT
Etat :  Hawaii
95 %
ECRIT
Etat :  Idaho
99 %
ECRIT
Etat :  Nevada
98 %
ECRIT
Etat :  Utah
91 %
ECRIT
Etat :  Arizona
80 %
ECRIT