您的位置:首页 > 编程语言 > Python开发

python(爬取大学排名)

2017-11-21 20:28 771 查看


import requests

from bs4 import BeautifulSoup

import bs4

def gethtml(url):

    try:

        r=requests.get(url,timeout=30)

        r.raise_for_status()

        r.encoding=r.apparent_encoding

        return r.text

    except:

        return ""

def fillUnivList(ulist,html):

    soup=BeautifulSoup(html,"html.parser")

    #arr=soup.find('tbody').contents #contents之后得到的是一个列表,

    #children就是用来遍历的

    #for tr in arr:

    #for tr in soup.tbody.children:三种遍历方法都行

    for tr in soup.find('tbody').children:

        if isinstance(tr,bs4.element.Tag):

            tds=tr('td') #把tr标签里面的td标签弄成列表的形式存起来

            #print('tds=',tds[0]),等价于tds=tr.find_all('td')

            ulist.append([tds[0].string,tds[1].string,tds[4].string])#取出tds列表中有用的三个,再次组合成一个列表,

            #放进另一个列表中,相当于二维列表

def pr(ulist,num):

    print("{:^10}  {:^6}  {:^10}".format("排名","学校","地址"))

    for i in range(num):

        u=ulist[i]

        print("{:^10} {:^6} {:^10}".format(u[0],u[1],u[2]))

def main():

    uinfo=[]

    url='http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'

    html=gethtml(url)

    fillUnivList(uinfo,html)

    pr(uinfo,10)

 

main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: