项目基本信息
目标网站:http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html
输入:大学排名URL链接
输出:大学排名信息的屏幕输出(排名,大学名称,总分)
技术路线:requests-bs4
定向爬虫:仅对输入 URL 进行爬取,不扩展爬取
程序的结构设计:
步骤1:从网络上获取大学排名网页内容 getHTMLText()
步骤2:提取网页内容中信息到合适的数据结构 fillUnivList()
步骤3:利用数据结构展示并输出结果 printUnivList()
目标网页样式:

相关知识
格式化字符串的函数: str.format()
基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。
一般用法:
"{} {}".format("hello", "world")
"{0} {1}".format("hello", "world")
"{1} {0} {1}".format("hello", "world")
"网站名:{name},地址:{url}".format(name="百度", url="www.baidu.com")
格式化输出:
^, <, >
分别是居中、左对齐、右对齐,后面带宽度,:
号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。+
表示在正数前显示 +,负数前显示 -;(空格)表示在正数前加空格。
b
、d
、o
、x
分别是二进制、十进制、八进制、十六进制。

数据 | 格式 | 输出 | 描述 |
---|---|---|---|
2.718 | {:.0f} | 3 | 不带小数 |
5 | {:0>2d} | 05 | 数字补零 (填充左边, 宽度为2) 十进制 |
1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
实例编写
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].string, tds[1].string, tds[3].string])
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]))
def main():
uinfo = []
url = 'https://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univs
main()
输出结果:

实例优化
当中文字符宽度不够时,采用西文字符填充;中西文字符占用宽度不同。采用中文字符的空格填充 char(12288)。
代码修改:
def printUnivList(ulist, num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",char(12288)))
for i in range(num):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],char(12288)))
:
前的索引对应后面的内容,:
后面为输出的格式,:{3}^10
表示以空格填充,宽度为 10 ,居中对齐,其中 3 即为空格的索引。
输出结果:

网友评论