选取非文本类型节点,需要import bs4
<>.() 等价于 <>.find_all()#查询该<>节点下全部某节点
soup() 等价于 souo.find_all()#查询全部某节点
输出中文对齐问题
#CrawUnivRankingB.py
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):#选取非文本节点类型,需要import bs4
tds = tr('td')#tds = tr.find_all('td')
ulist.append([tds[0].string, tds[1].string, tds[3].string])#列表
def printUnivList(ulist, num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))#chr(12288),表示以中文空格字符填充
for i in range(num):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
uinfo = []
url = 'https://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univs
main()