2020中国最好大学排名.py(亲测有效)
import requests from bs4 import BeautifulSoup import bs4 def getHTMLText(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") for tr in soup.find('tbody').children: if isinstance(tr,bs4.element.Tag): tds = tr('td') ulist.append([tds[0].text.strip(),tds[1].text.strip(),tds[4].text.strip()]) # strip函数移除空格或换行符 def printUnivList(ulist,num): tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}" # {3}表示使用format的第三个变量,即chr(12288)中文字符填充 print("{:^9}\t{:^15}\t{:^8}".format("排名","学校名称","分数")) for i in range(num): u = ulist[i] print(tplt.format(u[0],u[1],u[2],chr(12288))) def main(): uinfo = [] url = "https://www.shanghairanking.cn/rankings/bcur/2020" html = getHTMLText(url) fillUnivList(uinfo,html) printUnivList(uinfo,20) # 前20所 main()