python爬蟲入門---第二篇:獲取2019年中國大學排名
阿新 • • 發佈:2019-02-08
time 中國 form htm sts odin 代碼 網站 stat
我們需要爬取的網站:最好大學網
我們需要爬取的內容即為該網頁中的表格部分:
該部分的html關鍵代碼為:
其中整個表的標簽為<tbody>標簽,每行的標簽為<tr>標簽,每行中的每個單元格的標簽為<td>標簽,而我們所需的內容即為每個單元格中的內容。
因此編寫程序的大概思路就是先找到整個表格的<tbody>標簽,再遍歷<tbody>標簽下的所有<tr>標簽,最後遍歷<tr>標簽下的所有<td>標簽,
我們用二維列表來存儲所有的數據,其中二維列表中的每個列表用於存儲一行中的每個單元格數據,即<tr>標簽下的所有<td>標簽中的所有字符串。
代碼如下;
import requests from bs4 import BeautifulSoup import bs4 def get_html_text(url): ‘‘‘返回網頁的HTML代碼‘‘‘ try: res = requests.get(url, timeout = 6) res.raise_for_status() res.encoding = res.apparent_encoding return res.text except: return ‘‘ deffill_ulist(ulist, html): ‘‘‘將我們所需的數據寫入一個列表ulist‘‘‘ #解析HTML代碼,並獲得解析後的對象soup soup = BeautifulSoup(html, ‘html.parser‘) #遍歷得到第一個<tbody>標簽 tbody = soup.tbody #遍歷<tbody>標簽的孩子,即<tbody>下的所有<tr>標簽及字符串 for tr in tbody.children: #排除字符串 if isinstance(tr, bs4.element.Tag):#使用find_all()函數找到tr標簽中的所有<td>標簽 u = tr.find_all(‘td‘) #將<td>標簽中的字符串內容寫入列表ulist ulist.append([u[0].string, u[1].string, u[2].string, u[3].string]) def display_urank(ulist): ‘‘‘格式化輸出大學排名‘‘‘ print("{:^10}\t{:^10}\t{:^10}\t{:^10}".format("排名", "大學名稱", "省市", "總分")) for u in ulist: print("{:^10}\t{:^10}\t{:^10}\t{:^10}".format(u[0], u[1], u[2], u[3])) def write_in_file(ulist, file_path): ‘‘‘將大學排名寫入文件‘‘‘ with open(file_path, ‘w‘) as file_object: file_object.write("{:^5}\t{:^6}\t{:^10}\t{:^10}\n".format("排名", "大學名稱", "省市", "總分")) for u in ulist: file_object.write("{:^5}\t{:^6}\t{:^10}\t{:^10}\n".format(u[0], u[1], u[2], u[3])) def main(): ‘‘‘主函數‘‘‘ ulist = [] url = ‘http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html‘ file_path = ‘university rankings.txt‘ html = get_html_text(url) fill_ulist(ulist, html) display_urank(ulist) write_in_file(ulist, file_path) main()
打印顯示:
python爬蟲入門---第二篇:獲取2019年中國大學排名