为什么对象没有属性“ tbody”?

时间:2019-11-22 16:38:26

标签: python pandas dataframe beautifulsoup

我只是一个初学者python学习者,主要是由于我的工作而进行数据抓取,并且我试图找出没有属性'tbody'的原因.HTML中的tbody标记中很明显,它是怎么找不到的。这只是一个简单的Wikipedia数据抓取脚本,下面是可以帮助我的代码?

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL='https://en.wikipedia.org/wiki/List_of_countries_by_real_GDP_growth_rate'
response=requests.get(URL)
soup= BeautifulSoup(response.content, 'html.parser')
columns=['World Rank','Country','Real GDP Growth Rate %']

table=soup.find('table',{'class':'wikitable sortable jquery-tablesorter'}).tbody

df=pd.DataFrame(columns=columns)
trs=table.find_all('tr')

for tr in trs:
    tds = tr.find_all('td')
    row = [td.text.replace('\n','') for td in tds]
    df =df.append(pd.Series(row, index=columns),ignore_index=True)

df.to_csv('real gdp growth rate.csv', index=False)

1 个答案:

答案 0 :(得分:1)

如果您使用F12(又称开发工具)进行检查,即使原始代码中没有,它也会“总是”在任何表上显示提示消息。这应该足够了:

soup.find('table',{'class':'wikitable sortable jquery-tablesorter'}).findAll('tr')