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()
运行即可保存到相应的文件夹