import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
"""获取页面信息"""
try:
resp = requests.get(url, timeout=30)
resp.raise_for_status()
resp.encoding = resp.apparent_encoding
return resp.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')
ulist.append([tds[0].string,tds[1].string,tds[3].string])
def printUnivlist(ulist,num):
"""打印"""
uprint = '{0:^10}\t{1:{3}^10}\t{2:^10}'
print(uprint.format("排名", "学校名称", "总分",chr(12288)))
for i in range(num):
u = ulist[i]
print(uprint.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfor = []
url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
fillUnivlist(uinfor,html)
printUnivlist(uinfor,20)
main()