欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

使用Python爬取最好大学网大学排名

时间:2021-07-14 07:56:51|栏目:Python代码|点击:

本文实例为大家分享了Python爬取最好大学网大学排名的具体代码,供大家参考,具体内容如下

源代码:

#-*-coding:utf-8-*- 
''''' 
Created on 2017年3月17日 
@author: lavi 
''' 
import requests 
from bs4 import BeautifulSoup 
import bs4 
def getHTMLText(url): 
  try: 
    r = requests.get(url) 
    r.raise_for_status 
    r.encoding = r.apparent_encoding 
    return r.text 
  except: 
    return "" 
 
def fillUnivList(univList,html): 
  soup = BeautifulSoup(html,"html.parser") 
  for tr in soup.find("tbody").children: 
    if isinstance(tr,bs4.element.Tag): #tobody有的节点是空串,属于要判断类型进行过滤 
      tds = tr("td") #等价于tr.find_all("td") 
      univList.append([tds[0].string,tds[1].string,tds[2].string]) #NavigableString可以跨越多个层次 
 
def printUnivList(univList,num): 
  tplt = "{0:^6}\t{1:^10}\t{2:^6}" #:前的数字说明使用format函数的第几个参数填充模板 
  print(tplt.format("排名","学校名称","总分",chr(12288))) 
  for i in range(num): 
    u = univList[i] 
    print(tplt.format(u[0],u[1],u[2],chr(12288))) 
def main(): 
  url= "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html"; 
  html = getHTMLText(url) 
  univList=[] 
  fillUnivList(univList,html) 
  printUnivList(univList,20) 
   
main() 

上一篇:对python中list的拷贝与numpy的array的拷贝详解

栏    目:Python代码

下一篇:通过python扫描二维码/条形码并打印数据

本文标题:使用Python爬取最好大学网大学排名

本文地址:http://www.codeinn.net/misctech/157042.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有