用python爬取2021全国大学排行榜
作者:互联网
http://www.gaokao.com/e/20210328/606032dc1b634.shtml
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[2].text.strip()]) #.strip()去除头尾空格、换行
def printUnivList(ulist, num):
tplt = "{0:^12}\t.{1:{3}^10}\t.{2:^10}"
#print(tplt.format("排名", "学校名称", "总分", chr(12288)))
for i in range(num):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfo = []
url = 'http://www.gaokao.com/e/20210328/606032dc1b634.shtml'
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,34) # 20 univs
main()
标签:python,text,url,爬取,ulist,html,2021,strip,tds 来源: https://blog.csdn.net/qq_49783140/article/details/120104725