栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 抓取软科中国大学排名首页数据

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 抓取软科中国大学排名首页数据

1. 利用requests、BeautifulSoup、xlwings库抓取软科中国大学排名首页数据

(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()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/423687.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号