(1)软科中国大学排名网址
(2)调用requests模块中get方法,get方法包括headers参数,访问上述网址,获取Response 对象。
(3)利用BeautifulSoup类解析。
(4)利用find_all等方法查找tr、td等标签对象。
(5)将找到的相应标签内容依次添加到列表中。
(6)利用xlwings库,将列表内容写入Excel文件。
(7)将获取排名数据封装为一个方法。
(8)将抽取排名信息封装为一个方法。
(9)main()方法完成整体调用。
参考链接:
xlwings - 让Excel跑得飞快!
Excel VBA 参考
beautifulsoup 4
# -*- coding: utf-8 -*-
import requests as re
from bs4 import BeautifulSoup
import bs4
import xlwings as xw
def getSoup(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
web=re.get(url,timeout=30,headers=headers)
web.encoding=web.apparent_encoding
#BeautifulSoup将字节流转换为utf-8编码
bs_obj=BeautifulSoup(web.text,'lxml')
return bs_obj
except:
return ""
def findUniversity(soup):
ulist=[['排名','univ-logo','学校中文名称','学校英文名称','备注','省市','类型','总分','办学层次']]
for tr in soup.tbody.find_all('tr'):
if isinstance(tr, bs4.element.Tag):
tds = tr.find_all('td')
ulist.append([tds[0].text.strip(),
tds[1].find(class_="univ-logo").get('src'),
tds[1].find(class_="name-cn").text.strip(),
tds[1].find(class_="name-en").text.strip(),
tds[1].find(class_="tags").text.strip(),
tds[2].text.strip(),
tds[3].text.strip(),
tds[4].text.strip(),
tds[5].text.strip()])
return ulist
def main():
#获取BeautifulSoup对象
url = "https://www.shanghairanking.cn/rankings/bcur/2021"
soup = getSoup(url)
uinfo = findUniversity(soup)
#写入Excel文件
wb=xw.Book()
sht=wb.sheets('Sheet1')
sht.range('a1').value=uinfo#将数据添加到表格中
wb.close()
if __name__ == "__main__":
main()



