我是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
第一个问题来自:
}类。而是使用
^{pr2}$TableLeague
在这里是None
,因为没有table
元素具有{id
属性来查找所需的表元素:另外,您可能是指}这里:
strip()
而不是{col[1].a.string.stip()
。在并且,为了关闭文件,调用
close()
方法。替换:有:
或者,更好的方法是使用^{} context manager 来处理文件—您不需要显式地关闭文件。在
相关问题 更多 >
编程相关推荐