1 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
您從jurisdiction
列表開始,然后立即將其作為字典。然后,您將其視為 dict,直到您嘗試再次將其視為列表的錯(cuò)誤行。我認(rèn)為您在開始時(shí)需要為列表命名。可能您的意思是司法管轄區(qū)(復(fù)數(shù))作為列表。但是,IMO 還有另外兩個(gè)領(lǐng)域也肯定需要修復(fù):
find返回一個(gè)表。dict 中的標(biāo)簽/鍵表示您想要稍后的表(不是第一個(gè)匹配項(xiàng))
您的目標(biāo)表的索引不正確
你想要這樣的東西:
import requests, re
from bs4 import BeautifulSoup
response_obj = requests.get('https://en.wikipedia.org/wiki/Demographics_of_New_York_City').text
soup = BeautifulSoup(response_obj,'lxml')
Population_Census_Table = soup.select_one('.wikitable:nth-of-type(5)') #use css selector to target correct table.
jurisdictions = []
rows = Population_Census_Table.select("tbody > tr")[3:8]
for row in rows:
jurisdiction = {}
tds = row.select('td')
jurisdiction["jurisdiction"] = tds[0].text.strip()
jurisdiction["population_census"] = tds[1].text.strip()
jurisdiction["%_white"] = float(tds[2].text.strip().replace(",",""))
jurisdiction["%_black_or_african_amercian"] = float(tds[3].text.strip().replace(",",""))
jurisdiction["%_Asian"] = float(tds[4].text.strip().replace(",",""))
jurisdiction["%_other"] = float(tds[5].text.strip().replace(",",""))
jurisdiction["%_mixed_race"] = float(tds[6].text.strip().replace(",",""))
jurisdiction["%_hispanic_latino_of_other_race"] = float(tds[7].text.strip().replace(",",""))
jurisdiction["%_catholic"] = float(tds[10].text.strip().replace(",",""))
jurisdiction["%_jewish"] = float(tds[12].text.strip().replace(",",""))
jurisdictions.append(jurisdiction)
添加回答
舉報(bào)