跟随视频学习过程中,让我更加的理解了requests库和BeautifulSoup库的使用。虽然现在还有点生疏,不过我会更加努力的,让自己能熟练的使用这两个库。
下面贴出在中国最好大学网上爬取的代码:
1 import requests 2 from bs4 import BeautifulSoup 3 import bs4 4 5 def getHTMLText(url): 6 try: 7 r = requests.get(url, timeout=30) 8 r.raise_for_status() 9 r.encoding = r.apparent_encoding 10 return r.text 11 except: 12 return "" 13 14 def fillUnivList(ulist,html): 15 soup = BeautifulSoup(html,'html.parser') 16 for tr in soup.find('tbody').children: 17 if isinstance(tr,bs4.element.Tag): 18 tds = tr('td') 19 ulist.append([tds[0].string, tds[1].string, tds[2].string,tds[3].string]) 20 21 def printUnivList(ulist,num): 22 tplt = "{0:^10} {1:{4}^10} {2:^10} {3:^10}" 23 print(tplt.format("排名","学校名称","省份","分数",chr(12288))) 24 for i in range(num): 25 u = ulist[i] 26 print(tplt.format(u[0], u[1], u[2],u[3],chr(12288))) 27 28 def main(): 29 uinfo = [] 30 url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html" 31 html = getHTMLText(url) 32 fillUnivList(uinfo, html) 33 printUnivList(uinfo, 20) 34 35 main()
下面是运行结果: