import requests
import re
import bs4
from bs4 import BeautifulSoup
#提交URL获得html页面
def getHTMLText(url):
try:
r = requests.get(url,timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
soup = BeautifulSoup(html,"lxml")
tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[3].string])
#将ulist里面的内容打印输出
print(tplt.format("排名","学校","总分",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 = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html"
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20)
main()
import re
import bs4
from bs4 import BeautifulSoup
#提交URL获得html页面
def getHTMLText(url):
try:
r = requests.get(url,timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "error"
#html页面结构化提取存入ulist里面
soup = BeautifulSoup(html,"lxml")
for tr in soup.find('tbody').children:
#判断tr是否为标签类型
if isinstance(tr,bs4.element.Tag):tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[3].string])
#将ulist里面的内容打印输出
def printUnivList(ulist,num):
#定义输出模板为变量tplt,\t为横向制表符,^为中间对齐,10为每列的宽度,0,1,2代表format的格式
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"print(tplt.format("排名","学校","总分",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 = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html"
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20)
main()