日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python爬虫实例: 爬取“最好大学网”大学排名

發(fā)布時間:2023/12/29 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python爬虫实例: 爬取“最好大学网”大学排名 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

實例2 爬取大學排名

上海交通大學設(shè)計了一個“最好大學網(wǎng)”,上面列出了當前的大學排名。我們要設(shè)計爬蟲程序,爬取大學排名信息。

爬蟲功能要求:

輸入:大學排名URL鏈接
輸出:大學排名信息的屏幕輸出(排名,大學名稱,總分)
工具:python3、requests、beautifulsoup

程序設(shè)計思路:

  • 研究大學排名網(wǎng)站網(wǎng)頁URL
  • 設(shè)計fetchUrl函數(shù),嘗試獲取頁面;
  • 設(shè)計parseHtml函數(shù),解析內(nèi)容;
  • 設(shè)計output函數(shù),組織列表形式輸出;
  • 使用main函數(shù)調(diào)用程序。
  • import re import requests import bs4def fetchUrl(url):'''功能:根據(jù)參數(shù) url ,發(fā)起 http request,嘗試獲取指定網(wǎng)頁并返回結(jié)果參數(shù):url:某個 webpage 的url返回:類文件對象型 http Response 對象'''headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}try:r = requests.get(url, headers=headers)r.raise_for_status()r.encoding = r.apparent_encodingprint('success!')return r.textexcept requests.RequestError as e:print(e)except:return "Error!"def parserHtml(html,urating):'''功能:根據(jù)參數(shù) html 給定的內(nèi)存型 HTML 文件,嘗試解析其結(jié)構(gòu),獲取所需內(nèi)容參數(shù):html:類似文件的內(nèi)存 HTML 文本對象urating:一個二維列表,存放著大學排名信息返回:一個二維列表,存放著大學排名信息'''bsobj = bs4.BeautifulSoup(html,'html.parser')# 獲取表頭信息tr = bsobj.find('thead').find('tr')hlist = []if isinstance(tr, bs4.element.Tag):for th in tr('th'):hlist.append(th.string)hlist.pop()for option in tr('option'):hlist.append(option.string)urating.append(hlist)# 獲取表體信息for tr in bsobj.find('tbody').children:blist = []if isinstance(tr, bs4.element.Tag):for td in tr('td'):blist.append(td.string)urating.append(blist)return uratingdef output(urating, filename):'''功能:格式化輸出結(jié)果參數(shù):urating:存放著排名結(jié)果的二維列表filename:保存的文件名返回:無'''import pandas as pddataframe = pd.DataFrame(urating)dataframe.to_csv(filename, index=False, sep=',', header=False)print("Success!")def main():url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html'print("Begin to crawl the http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html and get the rating of universities in china ...")print('---'*20)print("Try to fetch url ...")html = fetchUrl(url)print("Try to parser html ...")urating = []ur = parserHtml(html,urating)print("Try to save the results in file ...")output(ur, '大學排名2018.csv')print("The work of crawling is done.")if __name__ == '__main__':main() Begin to crawl the http://www.zuihaodaxue.cn/zuihaodaxuepaiming2018.html and get the rating of universities in china ... ------------------------------------------------------------ Try to fetch url ... success! Try to parser html ... Try to save the results in file ... Success! The work of crawling is done.

    在程序?qū)崿F(xiàn)的時候,其實也是遇到了一些小坑,需要花一些小心思的。
    就是分析網(wǎng)頁的時候,發(fā)現(xiàn)表格最后一欄(得分指標)居然是一個下拉框,里面有很多指標選項,而且選擇不同的指標,表格中顯示的數(shù)據(jù)也不同。我需要根據(jù)它的實現(xiàn)原理來制定響應(yīng)的爬取策略。

    首先排除 url(因為整個過程中 url 是一直沒有變過),其次查看是否是 Ajax 異步加載,打開開發(fā)者工具監(jiān)測網(wǎng)頁,發(fā)現(xiàn)在切換指標選項時,并沒有發(fā)出新的請求,說明數(shù)據(jù)是一開始就已經(jīng)獲取好了的。隨后查看 Element ,定位到指標得分的這一列,然后發(fā)現(xiàn)...
    果然各個指標的數(shù)據(jù)都是有的,只是在頁面中隱藏了而已,所以,找好位置,可以放心的直接爬了(有一個小插曲,就是我擔心這些數(shù)據(jù)排列的順序跟表頭里指標的順序不一致而造成錯誤,但是后來對應(yīng)著表格里的數(shù)據(jù),驗證了幾行,發(fā)現(xiàn)這個擔心是多余的)。

    我覺得做爬蟲最關(guān)鍵的并不是做好某一個特定的爬蟲程序,最重要的是思路,雖然這里的擔心是多余的,但是有這個警覺性是很有必要的。

    總結(jié)

    以上是生活随笔為你收集整理的Python爬虫实例: 爬取“最好大学网”大学排名的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。