【Python爬蟲】從html裡爬取中國大學排名

來源:互聯網
上載者:User

標籤:app   空格   parent   學校   get   url   cep   ext   try   

from bs4 import BeautifulSoup
import requests
import bs4 #bs4.element.Tag時用的上
#擷取網頁頁面HTML
def getHTMLText(url):
try:
r = requests.request("get", url,timeout=30)
r.raise_for_status() #如不是200報錯
r.encoding = r.apparent_encoding #猜測編碼然後賦予給解碼 編碼模式
demo = r.text
soup = BeautifulSoup(demo, "html.parser") #做湯
return soup
except:
return ""
#分析並返回列表
def fillUnivList(ulist,html):
soup = html
for tr in soup.find("tbody").children: #從湯裡找tbody標籤的兒子遍曆
if isinstance(tr,bs4.element.Tag): #如果標籤是標籤名字
tds = tr("td") #尋找tr裡所有td列表,然後賦予tds
ulist.append([tds[0].string,tds[1].string,tds[3].string]) #加入013號
pass #???
#列印表格
def printUnivList(ulist,num):
tplt = "{0:^10}\t{1:{3}^8}\t{2:^10}" #模板
print(tplt.format("排名","學校名稱","總分",chr(12288))) #3號中文空格
for i in range(num):
u = ulist[i] #列表中的0是一個擁有三個元素的列表
print(tplt.format(u[0], u[1], u[2],chr(12288))) #擁有三個元素的列表按模板列印

print("Suc" + str(num))
#主函數
def main():
uinfo = [] #建立一個列表
url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html"
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20) #列印20個大學

main()

【Python爬蟲】從html裡爬取中國大學排名

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.