Python 如何使用Beauty Soup从网页的表中提取数据
我想从'https://statisticstimes.com/demographics/india/indian-states-population.php把它放在一个列表或字典里 我是Python的初学者。从目前为止我所学到的,我所能做的就是:Python 如何使用Beauty Soup从网页的表中提取数据,python,beautifulsoup,Python,Beautifulsoup,我想从'https://statisticstimes.com/demographics/india/indian-states-population.php把它放在一个列表或字典里 我是Python的初学者。从目前为止我所学到的,我所能做的就是: 导入urllib.request、urllib.error、urllib.parse 从bs4导入BeautifulSoup url=输入(“输入url:”) html=urllib.request.urlopen(url.read()) x=Bea
导入urllib.request、urllib.error、urllib.parse
从bs4导入BeautifulSoup
url=输入(“输入url:”)
html=urllib.request.urlopen(url.read())
x=BeautifulSoup(html,'html.parser')
标记=x('tr')
lst=列表()
对于标记中的标记:
lst.append(tag.findAll('td'))
打印(lst)
您可以使用请求
和熊猫
以下是方法:
将熊猫作为pd导入
导入请求
从表格导入表格
url=”https://statisticstimes.com/demographics/india/indian-states-population.php"
df=pd.read_html(requests.get(url.text,flavor=“bs4”)[-1]
打印(制表(测向头(10),显示索引=假))
输出:
--- ---------------- -------- -------- ------- ----- ---- -------------------- ---
NCT Delhi 18710922 16787941 1922981 11.45 1.36 Malawi 63
18 Haryana 28204692 25351462 2853230 11.25 2.06 Venezuela 51
14 Kerala 35699443 33406061 2293382 6.87 2.6 Morocco 41
20 Himachal Pradesh 7451955 6864602 587353 8.56 0.54 China, Hong Kong SAR 104
16 Punjab 30141373 27743338 2398035 8.64 2.2 Mozambique 48
12 Telangana 39362732 35004000 4358732 12.45 2.87 Iraq 36
25 Goa 1586250 1458545 127705 8.76 0.12 Bahrain 153
19 Uttarakhand 11250858 10086292 1164566 11.55 0.82 Haiti 84
UT3 Chandigarh 1158473 1055450 103023 9.76 0.08 Eswatini 159
9 Gujarat 63872399 60439692 3432707 5.68 4.66 France 23
--- ---------------- -------- -------- ------- ----- ---- -------------------- ---
与:
您可以将表转储到.csv
文件:
df.to_csv("your_table.csv", index=False)