前提
pyhonでポケモンsvのデータをまとめた、jsonファイルを作っています。
ポケモンの情報を取得できたですが、
for文のzipで合体させるとjsonに出力したときに内容がすべてバラバラ(?)になってしまう
長くなっていしまってすいませんm(__)m
実現したいこと
・jsonファイルの鍵かっこ{}の位置を調節・不必要な{}の削除
・jsonファイルの","の位置の調整
該当のソースコード
python
1page_url = "https://altema.jp/pokemonsv/pokemonlist" 2 3r = requests.get(page_url) 4soup = BeautifulSoup(r.text, features="html.parser") 5 6numbers_list = [] 7names_list = [] 8type_img_list = [] 9img_urls_list = [] 10hps_list = [] 11nums_list =[] 12habitat_list = [] 13habitat_url_list = [] 14 15#ポケモンの番号を取得 16numbers = soup.find_all("div",attrs={"class": "number"}) 17for number in numbers: 18 numbers_list.append(number.text) 19 #print(number.text) 20 21 22#ポケモンの名前を取得 23names = soup.find_all("div",attrs={"class": "name"}) 24for name in names: 25 names_list.append(name.text) 26 27#ポケモンのtypeを取得 28target_keys = ["type1","type2"] 29def filtered_data(row): 30 data = json.loads(row['data-obj']) 31 return {k: data[k] for k in target_keys} 32 33type_list = [*map(filtered_data, soup.select('#result_table tr[data-obj]'))] 34#pprint(type_list) 35 36 37#ポケモン画像urlを取得 38img_urls = soup.find_all("img",attrs={"class":"aligncenter iconsize-60"}) 39for img_url in img_urls: 40 img = img_url.get("data-lazy-src") 41 img_urls_list.append(img) 42 43 44#ステータスを取得 45hps = soup.find_all("div",attrs={"class": "syuzokuchi"}) 46 47for status in hps: 48 status = [s.text.strip() for s in status.find_all('span')] 49 status = dict(zip(status[::2], status[1::2])) 50 hps_list.append(status) 51 52#ポケモンの情報を合体させる 53for pk_name,pk_number,pk_img,pk_hp,pk_type in zip(names_list,numbers_list,img_urls_list,hps_list,type_list): 54 deta = { 55 pk_name:{ 56 "number": pk_number, 57 "name": pk_name, 58 "type" : pk_type, 59 "url" : pk_img, 60 "status" : pk_hp, 61 }, 62 } 63 with open('pokemon_deta.json', 'a') as f: 64 json.dump(deta,f,ensure_ascii=False,indent=4) 65 print(deta)
pokemon_deta.json
json
1{ 2 "ニャオハ": { 3 "number": "No.001", 4 "name": "ニャオハ", 5 "type": { 6 "type1": 5, 7 "type2": 0 8 }, 9 "url": "https://img.altema.jp/pokemonsv/pokemon/icon/237.png", 10 "status": { 11 "HP": "40", 12 "攻撃": "61", 13 "防御": "54", 14 "特攻": "45", 15 "特防": "45", 16 "素早": "65", 17 "合計": "310" 18 } 19 } 20}{ 21 "ニャローテ": { 22 "number": "No.002", 23 "name": "ニャローテ", 24 "type": { 25 "type1": 5, 26 "type2": 0 27 }, 28 "url": "https://img.altema.jp/pokemonsv/pokemon/icon/238.png", 29 "status": { 30 "HP": "61", 31 "攻撃": "80", 32 "防御": "63", 33 "特攻": "60", 34 "特防": "63", 35 "素早": "83", 36 "合計": "410" 37 } 38 } 39}{ 40 "マスカーニャ": { 41 "number": "No.003", 42 "name": "マスカーニャ", 43 "type": { 44 "type1": 5, 45 "type2": 16 46 }, 47 "url": "https://img.altema.jp/pokemonsv/pokemon/icon/239.png", 48 "status": { 49 "HP": "76", 50 "攻撃": "110", 51 "防御": "70", 52 "特攻": "81", 53 "特防": "70", 54 "素早": "123", 55 "合計": "530" 56 } 57 } 58} 59.... 60... 61.. 62.
試したこと
Googleでの検索
補足情報(FW/ツールのバージョンなど)
vscode
python 3.10.0

回答1件
あなたの回答
tips
プレビュー