【发布时间】:2016-11-06 22:48:32
【问题描述】:
有可能(是否有简单的方法)从网站中获取表格,然后将其转换为图表而不是表格?
这是代码将表格提取到表格中的代码。
导入用于查询网站的库
import urllib2
#specify the url
wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
#Query the website and return the html to the variable 'page'
page = urllib2.urlopen(wiki)
#import the Beautiful soup functions to parse the data returned from the website
from bs4 import BeautifulSoup
#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page)
all_tables=soup.find_all('table')
right_table=soup.find('table', class_='wikitable sortable plainrowheaders')
right_table
#Generate lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
for row in right_table.findAll("tr"):
cells = row.findAll('td')
states=row.findAll('th') #To store second column data
if len(cells)==6: #Only extract table body not heading
A.append(cells[0].find(text=True))
B.append(states[0].find(text=True))
C.append(cells[1].find(text=True))
D.append(cells[2].find(text=True))
E.append(cells[3].find(text=True))
F.append(cells[4].find(text=True))
G.append(cells[5].find(text=True))
#import pandas to convert list to data frame
import pandas as pd
df=pd.DataFrame(A,columns=['Number'])
df['State/UT']=B
df['Admin_Capital']=C
df['Legislative_Capital']=D
df['Judiciary_Capital']=E
df['Year_Capital']=F
df['Former_Capital']=G
df
【问题讨论】:
-
什么图?你的意思是一些情节? pandas 具有绘图功能 - 检查文档。
-
是的,一个简单的情节。
-
df.plot()?pandas使用matplotlib以便您可以在matplotlib文档中找到更多信息。 -
我是这方面的初学者(如果我可以说一周大)。我试图找出自己的解决方案。但是,我们将非常感谢您对代码的任何帮助。
标签: python pandas beautifulsoup