今天看python爬虫的视频,然后按照视频上的内容编写代码,运行时出现了AttributeError: 'NoneType' object has no attribute 'children'错误提示,看了好久代码也没发现错误,百度了网上有个博主发布了一条博客,发现他也是一样的错误,看了他的博客,然后再看我的代码,发现我们都是同一个单词写错了,代码如下:
# 爬取由上海交通大学开发的最好大学网 http://www.zuihaodaxue.cn/
# 中国大学排名网页 http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url,timeoout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist,html):
soup = BeautifulSoup(html,'html.parser')
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[2].string])
def printUnivList(ulist,num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))
for i in range(num):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html'
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20) #20 表示取前20所大学
main()
运行程序后的错误提示:
for tr in soup.find('tbody').children:
AttributeError: 'NoneType' object has no attribute 'children'
感谢博主的分享,让我很快找出了错误。
错误代码:r = requests.get(url,timeoout=30)将单词 timeoout 改成 timeout 就解决了这个Bug
我用自己的想法解析一下错误的原因:
属性错误:'NoneType' 对象没有属性 'children' ,这个错误提示告诉我们 'children' 属性的对象 soup 是一个空类型,那就意味着soup = BeautifulSoup(html,'html.parser')中soup并没有得到解析出来的html页面,那就是说在调用getHTMLText(url)函数时这个函数并没有得到url链接对应的网页信息。所以错误可能出现在getHTMLText(url)函数中,然后仔细审查getHTMLText(url)函数中代码发现单词打错。
总之:这四个函数之间各有分工,但是又紧密相连,任何一个出现问题都可能导致其它函数报错,所以我们找错时不能只局限于报错的那一行代码
版权声明:本文为qq_36525166原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。