AttributeError: 'NoneType' object has no attribute 'children' 错误

Tertia ·
更新时间:2024-09-20
· 558 次阅读

在运行嵩天老师python爬虫课中单元6中的实例“中国大学排名爬虫”会出现如下图错误:AttributeError: ‘NoneType’ object has no attribute ‘children’
在这里插入图片描述
意思是 ‘NoneType’ 对象没有属性 ‘children’ ,这个错误说明’children’ 属性的对象 soup 是一个空类型,那就意味着soup = BeautifulSoup(html,‘html.parser’)中soup并没有得到解析出来的html页面,那就是说在调用getHTMLText(url)函数时这个函数并没有得到url链接对应的网页信息。错误就出在getHTMLText(url)函数之中,可是仔细审查一遍后发现并没有错误。
那所有的所有都指向了最后的一个可能,真相只有一个,那就是url地址有问题。
嵩天老师的实例给出的url地址是https://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html
本着柯南的精神,那就去浏览器试一下,结果如下图:
在这里插入图片描述
果然没错,就是url地址错误了!!!
然后百度了一下最好大学网,发现正确的地址应该是:
http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html
结果就是http没有s,cn是com
修改后运行结果:
在这里插入图片描述
最后贴上代码:

import requests from bs4 import BeautifulSoup import bs4 def getHTMLText(url): try: r = requests.get(url, timeout=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[3].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.com/zuihaodaxuepaiming2018.html' html = getHTMLText(url) fillUnivList(uinfo, html) printUnivList(uinfo, 20) # 20 univs main()
作者:cleverlovex



has children object

需要 登录 后方可回复, 如果你还没有账号请 注册新账号