python3爬虫-中国最好大学排名
使用python的requests和BeautifulSoup爬取前20個中國最好的大學,內容來源于最好大學這個網站,不需要登陸,直接可以訪問靜態(tài)網頁內容,網頁如下:
直接可以提取信息,非常適合練習requests和BeautifulSoup功能.
主程序需要幾個部分組成
首先載入必要的包
import requests from bs4 import BeautifulSoup import bs4getHTMLText函數(shù):訪問網頁,得到html信息到本地,方便下一步的處理
def getHTMLText(url):try:r = requests.get(url, timeout = 30)r.raise_for_status()#返回狀態(tài).200為正常,如果有問題,這里可以顯示出問題所在r.encoding = r.apparent_encoding#分析內容編碼方式,防止出現(xiàn)亂碼return r.textexcept:return ''fillUnivList函數(shù),得到getHTMLText函數(shù)的html信息,進行內容解析,將需要的內容傳送到ulist中
看網頁源代碼發(fā)現(xiàn)我們要的信息都在tbody內的 tr標簽的td內,函數(shù)如下
def fillUnivList(ulist, html):soup = BeautifulSoup(html ,'html.parser')#用parser進行解析for tr in soup.find('tbody').children: #在tbody內部查找if isinstance(tr,bs4.element.Tag): #篩選標簽部分tds = tr('td') #找到核心內容ulist.append([tds[0].string, tds[1].string, tds[2].string])return ulist最后使用printUnivList函數(shù)進行打印
def printUnivList(ulist, num):print('{:^10}\t{:^6}\t{:^10}'.format('排名','學校名稱','總分'))for i in range(num):u = ulist[i]print('{:^10}\t{:^6}\t{:^10}'.format(u[0], u[1], u[2]))
三個函數(shù)部分都寫完了,最后使用一個主函數(shù)進行函數(shù)連接
def main():uinfo = []url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html'html = getHTMLText(url)fillUnivList( uinfo ,html)printUnivList(uinfo, 20)輸入main()
? ? 排名? ? ? ? ? ?學校名稱? ? ? ?總分? ??
? ? 1? ? ? ? ? ? 清華大學? ? ? ?北京? ??
? ? 2? ? ? ? ? ? 北京大學? ? ? ?北京? ??
? ? 3? ? ? ? ? ? 浙江大學? ? ? ?浙江? ??
? ? 4? ? ? ? ? ?上海交通大學? ? ? 上海? ??
? ? 5? ? ? ? ? ? 復旦大學? ? ? ?上海? ??
? ? 6? ? ? ? ? ?中國科學技術大學? ? ? ? ? ? 安徽? ??
? ? 7? ? ? ? ? ? 南京大學? ? ? ?江蘇? ??
? ? 8? ? ? ? ? ?華中科技大學? ? ? 湖北? ??
? ? 9? ? ? ? ? ? 中山大學? ? ? ?廣東? ??
? ? 10? ? ? ? ? 哈爾濱工業(yè)大學? ? 黑龍江? ??
? ? 11? ? ? ? ? ?同濟大學? ? ? ?上海? ??
? ? 12? ? ? ? ? ?武漢大學? ? ? ?湖北? ??
? ? 13? ? ? ? ? ?東南大學? ? ? ?江蘇? ??
? ? 14? ? ? ? ? 西安交通大學? ? ? 陜西? ??
? ? 15? ? ? ? ? 北京航空航天大學? ? ? ? ? ? 北京? ??
? ? 16? ? ? ? ? ?南開大學? ? ? ?天津? ??
? ? 17? ? ? ? ? ?四川大學? ? ? ?四川? ??
? ? 18? ? ? ? ? ?天津大學? ? ? ?天津? ??
? ? 19? ? ? ? ? 華南理工大學? ? ? 廣東? ??
? ? 20? ? ? ? ? 北京師范大學? ? ? 北京?
總結:首先對url提取html信息,第二部對html信息提取關鍵部分,這里需要對網頁源代碼進行觀察,找到提取信息的方法,也是代碼的核心部分,最后進行打印.
總結
以上是生活随笔為你收集整理的python3爬虫-中国最好大学排名的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot小型超市商品展销系统
- 下一篇: paper plane fly away