2017-03-14 58 views
2

解析器获得中国最好的大学名单。我得到“NoneType”对象有没有属性'孩子”的错误信息:使用BeautifulSoup得到''NoneType'对象没有属性'children'“

File "C:/Projects/Beijing Python/Week 2/Unit 06.py", line 22, in fillUnivList for tr in soup.find('tbody').children:

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

如果我检查码的手动,声明是确定‘soup.find(‘TBODY’)的孩子。’怎么了?

import requests 
from bs4 import BeautifulSoup 
import bs4 
def getHTMLText(url): 
    try: 
     r = requests.get(url, timeout=30) 
     r.raise_for_stasus() 
     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): 
    print("{:^10}\t{:^6}\t{:^10}".format('排名', '学校名称', '总分')) 
    for i in range(num): 
     u = ulist[i] 
     print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2])) 


def main(): 
    uinfo = [] 
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html' 
    html = getHTMLText(url) 
    fillUnivList(uinfo, html) 
    printUnivList(uinfo, 20) 
main() 

回答

2

我假设你request对象没有raise_for_stasus()。这是一个错字 - 它是raise_for_status()。您也可以使用status_code

def getHTMLText(url): 
    try: 
     r = requests.get(url, timeout=30) 
     if r.status_code == 200: 
      r.encoding = r.apparent_encoding 
      return r.text 
    except Exception, e: 
     print (e) 
     return "" 

并改变你的findfor tr in soup.find('tbody', class_="hidden_zhpm").children:

似乎工作。

+0

你为什么喜欢检查status_code? –

+0

再一次,什么是class _ =“hidden_​​zhpm?我在google中找不到任何关于它的信息 –

+0

个人选择,可以使用raise来提出错误或者检查你想要的类型,你可以找到一个html元素通过它的类,这就是'class_'的用途。 – Zroq

相关问题