0.中国大学排名定向爬虫
http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html
可行性:
http://www.zuihaodaxue.cn/robots.txt
数据在Html里
出错的原因+函数名写错了
import requests
from bs4 import BeautifulSoup
import bs4 # if isinstance(tr,bs4.element.Tag):#不是标签的都不执行:
def getHTMLText(url):#将url信息爬取下来
try:
r=requests.get(url,timeout=300)
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')#相当于tr.find_all('td')
ulist.append([tds[0].string,tds[1].string,tds[2].string],tds[3].string)
#tds[0]是这样的<td><div align="left">清华大学</div></td> tds[1]是这样的<td>北京市</td>
#tds[2]是这样的<td>95.9</td>
#插入列表中
def printUnivList(ulist,num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
#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]))
print(tplt.format(u[0],u[1],u[2],chr(12288))
print("suc"+str(num))
def main():
uinfo = []#大学信息放在列表中
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html=getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo, 20) # 第二个参数为显示信息个数
# def main():
# uinfo=[]
# url='http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html'
# html=getHTMLText(url)
# fillUnivList(uinfo, html)
# printUnivList(uinfo, 20) # 20 表示取前20所大学
main()
summary