python爬虫 AttributeError: 'NoneType' object has no attribute 'children' 错误

1.对AttributeError: ‘NoneType’ object has no attribute 'children’的解决办法

很多人出现这个问题很有可能都是看完中国大学生慕课python爬虫教程视频后练习代码出现的,这里指出一下,老师的代码是没有问题的,出现这个问题你需要在getHTMLText(url)fillUnivList(ulist,html)这两个函数模块仔细检查代码是否有写错,比如:英文字母多写或少写,csdn中也有类似文章提到了代码写错导致出错的问题,so,建议你仔细检查自己的代码是否有写错!

2.对原代码增加自动保存爬取下来的数据功能

原代码主要是实现数据的部分获取,这可能在实际需求中不能满足,实际过程中需要完整的数据并保存,因此增加一个用pandas来保存的小模块。
代码如下:

#中国大学定向排名数据爬取
#2019.10.11
import requests
from bs4 import BeautifulSoup
import bs4
import os
import pandas

def getHTMLText(url):#获取HTML网页
    try:
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return (r.text)
    except:
        return ""
        
def fillUnivList(ulist,html):#获取网页所需信息,输出到ulist列表中
    soup = BeautifulSoup(html,"lxml")
    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,tds[3].string,tds[4].string])
          
def saveFile(root,name,ulist):#保存数据
    path = root + name
    try:
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            file = pd.DataFrame(ulist,columns = ["排名","学校","地区","总分","指标得分"])
            file.to_csv(path,index = False,sep = ",")
            print("Save successfuly!")
        else:
            print("The path already exist!")
    except:
        print("Save Filed!")
        
def main():#主函数
    uinfo = []
    root = "D://爬虫练习文件夹//"
    name = "中国大学排名2016"
    url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html"
    html = getHTMLText(url)
    fillUnivList(uinfo,html)
    saveFile(root,name,uinfo)
main()

运行即可保存到相应的文件夹

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值