# coding=gbk
import requests
from bs4 import BeautifulSoup
import bs4
class Ranking:
def getHtml(self,url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def urlList(self,numberList,schoolList,scoreList, html):
try:
soup = BeautifulSoup(html, "html.parser")
##匹配带有class属性的tbody标签
tbodyInfo = soup.find("tbody", attrs={'class': 'hidden_zhpm'})
if isinstance(tbodyInfo,bs4.element.Tag):
#找到tbody下的tr标签
trList = tbodyInfo.find_all('tr')
for tdTag in trList:
#在每个tr标签下,查找所有的td标签
tdList = tdTag.find_all('td')
#通过角标获取所要的值
count = tdList[0].string
numberList.append(count)
schoolName = tdList[1].string
schoolList.append(schoolName)
scores = tdList[3].string
scoreList.append(scores)
return numberList,schoolList,scoreList
except Exception as e:
print(e)
def printList(self, num):
try:
with open("data2.txt",'w',encoding='utf-8') as f:
for i in range(num):
f.write("{0:^10}\t{1:{3}^10}\t{2:^10}".format(numberList[i], schoolList[i], scoreList[i],chr(12288)))
f.write('\n')
except IOError as e:
print(e)
if __name__ == '__main__':
numberList = []
schoolList = []
scoreList = []
url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
rank = Ranking()
html = rank.getHtml(url)
rank.urlList(numberList,schoolList,scoreList,html)
rank.printList(len(numberList))
中国大学排名定向爬虫
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Python版本:Python3.5 ;技术路线:requests-bs4 。 功能描述: 俗话说“有人的地方就有...