此为中国大学mooc中python爬虫的学习笔记
采用requests库和 BeautifulSoup库
功能描述
爬取大学排名数据输出排名情况
前期准备:
robots协议 在浏览器中输入 https://www.shanghairanking.cn/rankings/bcur/2021/robots.txt 发现没有robots协议
程序结构设计:
1.从网页中爬取排名内容def getHTMLText(url) 2.提取网页内容中信息到合适的数据结构:def fillUnivList(ulist, html) 3.利用数据结构展示并输出结果:def printUnivList(ulist, num)
完整代码:
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()])
def printUnivList(ulist, num):
print("{:^10}{:^6} {:^10}".format("排名", "学校", "总分"))
for i in range(num):
u = ulist[i]
print("{:^10} {:^6} {:^10}".format(u[0], u[1], u[2]))
def main():
uinof = []
url = 'https://www.shanghairanking.cn/rankings/bcur/2021'
html = getHTMLText(url)
fillUnivList(uinof, html)
printUnivList(uinof, 20)
main()
|