Learn practical skills, build real-world projects, and advance your career
import requests
import json
from bs4 import BeautifulSoup

''' Method 1. List of Dictionaries '''
def voting_list(state,ward_no):
    payload = {
        'state':f'{state}',
        'district':'26',
        'vdc_mun':'5278',
        'ward':f'{ward_no}',
        'reg_centre':''
            }
    url = 'https://voterlist.election.gov.np/bbvrs/view_ward_1.php'
    response = requests.post(url,data=payload)
    soup = BeautifulSoup(response.text,"html.parser") 
    div = soup.find('div',class_='div_bbvrs_data')
    table = div.find("table")
    head_table_data = ['voter_id','voter_name','age','gender','wife/husband_name','father/mother_name']
    body_table_data = table.tbody.find_all("tr")  
    list_data = []
    for count in range(len(body_table_data)):
        dict_data = {}
        # for data in body_table_data[i].find_all("td"):
        for i,th in enumerate(head_table_data):
            dict_data[th] = body_table_data[count].find_all("td")[i+1].get_text()   
        list_data.append(dict_data)
    string_list_data = str(list_data)
    numbers_map = {'0': '०','1': '१','2': '२','3': '३','4': '४','5': '५','6': '६','7': '७','8': '८','9': '९'}
    for eng_num,unicode in numbers_map.items():
        string_list_data = string_list_data.replace(eng_num,unicode)
    # bytestring = string_list_data.encode("utf-8")
    # json_str = json.dumps(string_list_data,ensure_ascii=False).encode('utf8')
    # with open(f'voting_list_wards{ward_no}.json','wb',encoding='utf8') as file:
    #     file.write(bytestring)
    with open(f'voting_list_wards{ward_no}.json','w',encoding='utf8') as file:
        json.dump(string_list_data,file,ensure_ascii=False)


voting_list(3,1)  
# bytestring = string_list_data.encode("utf-8")
# json_str = json.dumps(string_list_data,ensure_ascii=False).encode('utf8')
# with open(f'voting_list_wards{ward_no}.json','wb',encoding='utf8') as file:
#     file.write(bytestring)