TypeError:“NoneType”对象在刮取时不可调用

2024-05-23 23:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,尝试从web上获取数据(最终)提供给一个小型数据库。在

我的代码正在生成NoneType错误。你能帮忙吗?在

import urllib2
from bs4 import BeautifulSoup
    #1- create files to Leagues, stock data and error
FLeague= open("C:\Python\+exercice\SoccerLeague.txt","w")
FData=open("C:\Python\+exercice\FootballDump.txt","w")
ErrorFile=open("C:\Python\+exercice\ErrorFootballScrap.txt","w")
#Open the website
# 1- grab the data and get the error too
soup = BeautifulSoup(urllib2.urlopen("http://www.soccerstats.com/leagues.asp").read(),"html")
TableLeague =  soup.find("table", {"class" : "trow8"})
print TableLeague
#\here I just want to grab country name
for row in TableLeague("tr")[2:]:
       col = row.findAll("td")
# I try to identify errors
       try:
          country = col[1].a.string.stip()
          FLeague.write(country+"\n")
       except Exception as e:
          ErrorFile.write (country + ";" + str(e)+";"+str(col)+"\n")
          pass
    #close the files
FLeague.close
FData.close
ErrorFile.close

Tags: thetoimporttxtclosecolfilesopen
1条回答
网友
1楼 · 发布于 2024-05-23 23:38:43

第一个问题来自:

TableLeague("tr")[2:]

TableLeague在这里是None,因为没有table元素具有{}类。而是使用id属性来查找所需的表元素:

^{pr2}$

另外,您可能是指strip()而不是{}这里:col[1].a.string.stip()。在

并且,为了关闭文件,调用close()方法。替换:

FLeague.close
FData.close
ErrorFile.close

有:

FLeague.close()
FData.close()
ErrorFile.close()

或者,更好的方法是使用^{} context manager来处理文件—您不需要显式地关闭文件。在

相关问题 更多 >