如何使用python bs4获取wikipedia表中的第一列值?

如何使用python bs4获取wikipedia表中的第一列值?,python,pandas,web-scraping,beautifulsoup,Python,Pandas,Web Scraping,Beautifulsoup,我正在尝试使用PythonBS4在wikipedia中对数据表进行web抓取。但是我被这个问题困住了。获取数据值时,我的代码没有获取第一列或索引零。我觉得索引有问题,但我想不出来。请帮忙。见 response_obj = requests.get('https://en.wikipedia.org/wiki/Metro_Manila').text soup = BeautifulSoup(response_obj,'lxml') Neighborhoods_MM_Table = soup.fin

我正在尝试使用PythonBS4在wikipedia中对数据表进行web抓取。但是我被这个问题困住了。获取数据值时,我的代码没有获取第一列或索引零。我觉得索引有问题,但我想不出来。请帮忙。见

response_obj = requests.get('https://en.wikipedia.org/wiki/Metro_Manila').text
soup = BeautifulSoup(response_obj,'lxml')
Neighborhoods_MM_Table = soup.find('table', {'class':'wikitable sortable'})

rows = Neighborhoods_MM_Table.select("tbody > tr")[3:8]

cities = []
for row in rows:
    city = {}
    tds = row.select('td')
    city["City or Municipal"] = tds[0].text.strip()
    city["%_Population"] = tds[1].text.strip()
    city["Population"] = float(tds[2].text.strip().replace(",",""))
    city["area_sqkm"] = float(tds[3].text.strip().replace(",",""))
    city["area_sqm"] = float(tds[4].text.strip().replace(",",""))
    city["density_sqm"] = float(tds[5].text.strip().replace(",",""))
    city["density_sqkm"] = float(tds[6].text.strip().replace(",",""))

    cities.append(city)

print(cities)

df=pd.DataFrame(cities)

df.head() 

导入请求
从bs4导入BeautifulSoup
作为pd进口熊猫
def主(url):
r=请求。获取(url)
soup=BeautifulSoup(r.content'html.parser')
target=[item.get_text(strip=True)表示soup.findAll中的项(
“td”,style=“text align:right”),如果item.text中的“%”为+[“”]
df=pd.read_html(r.content,header=0)[5]
df=df.iloc[1:-1]
df['人口(2015)[3]']=目标
打印(df)
df.to_csv(“data.csv”,index=False)
主要(”https://en.wikipedia.org/wiki/Metro_Manila")
输出:

导入请求
从bs4导入BeautifulSoup
作为pd进口熊猫
def主(url):
r=请求。获取(url)
soup=BeautifulSoup(r.content'html.parser')
target=[item.get_text(strip=True)表示soup.findAll中的项(
“td”,style=“text align:right”),如果item.text中的“%”为+[“”]
df=pd.read_html(r.content,header=0)[5]
df=df.iloc[1:-1]
df['人口(2015)[3]']=目标
打印(df)
df.to_csv(“data.csv”,index=False)
主要(”https://en.wikipedia.org/wiki/Metro_Manila")
输出:


请提供一个您必须将代码作为
代码
,而不是
图片
,以便我们可以手动验证和检查。请提供一个您必须将代码作为
代码
,而不是
图片
,以便我们可以手动验证和检查。