【问题标题】:"How to fix 'AttributeError: 'NoneType' object has no attribute 'tbody'' error in Python?“如何修复 Python 中的 'AttributeError: 'NoneType' 对象没有属性 'tbody'' 错误?
【发布时间】:2019-07-05 21:27:28
【问题描述】:

我希望在我的桌面目录中创建一个 csv 文件。

导入请求 从 bs4 导入 BeautifulSoup 将熊猫导入为 pd

url = "https://basketball.realgm.com/ncaa/conferences/Big-12- 
Conference/3/Kansas/54/nba-players"

# get permission
response = requests.get(url)

# access html files
soup = BeautifulSoup(response.text, 'html.parser')

 # creating data frame
columns = ['Player', 'Position', 'Height', 'Weight', 'Draft Year', 'NBA 
Teams', 'Years', 'Games Played','Points Per Game', 'Rebounds Per Game', 
'Assists Per Game']

df = pd.DataFrame(columns=columns)

table = soup.find(name='table', attrs={'class': 'tablesaw','data- 
tablesaw-mode':'swipe','id': 'table-6615'}).tbody

trs = table.find('tr')

# rewording html

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('kansas_player', index=False)

我希望在我的桌面目录中创建一个 csv 文件。

【问题讨论】:

  • 请帮助我刚刚开始进行网络解析。
  • 如果soup.find('table') 找不到任何表怎么办?
  • 请发布完整的回溯,这有助于了解错误发生在哪里

标签: python pandas beautifulsoup html-parsing


【解决方案1】:

按照您的方式,soup.find(...) 似乎找不到“table”,这可能 这就是为什么您返回 None 类型的原因,这是我的更改,您可以对其进行定制以满足您的 csv 导出需求:

from bs4 import BeautifulSoup
import urllib.request

url = "https://basketball.realgm.com/ncaa/conferences/Big-12-Conference/3/Kansas/54/nba-players"

# get permission
response = urllib.request.urlopen(url)

# access html files
html = response.read()
soup = BeautifulSoup(html)
table = soup.find("table", {"class": "tablesaw"})

此时,您可以将完整的table 内容返回为:

从那里,您可以通过以下方式轻松提取表格行信息:

for tr in table.findAll('tr'):
    tds = tr.find_all('td')
    row = [td.text.replace('\n', '')for td in tds]
    .....

现在每一行看起来像:

最后,您可以在有或没有熊猫的情况下将每一行写入 csv,然后由您来决定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多