Python爬虫_大学专业排名


前言

刚学中国大学MOOC(嵩天 北京理工大学)上的网络爬虫不久,想着如何加深课后理解,就去爬取中国大学自动化专业排名,写篇博客记录一下


提示:以下是本篇文章正文内容,下面内容供学习参考使用

一、原网络

1.原地址:

大学生必备网-控制科学与工程专业大学排名
https://www.dxsbb.com/news/7564.html

2.爬取内容:

爬取序号、学校代码、学校名称、评选结果
控制科学与工程专业排名

二、编程

1.编程思路

具体编程思路可查看嵩天老师的课程视频:

中国大学MOOC Python网络爬虫与信息提取
https://www.icourse163.org/course/BIT-1001870001

2.编程

大部分代码可参考原视频代码
fillUnivList()函数:

查看网络源代码
网络源代码
可以看到在父节点tbody下,每个tr包含一个大学的信息,每部分信息又由td组成

代码如下:

def fillUnivList(ulist, html):
    try:
        soup = BeautifulSoup(html, 'html.parser')
        for tr in soup.find('tbody').children:
            if isinstance(tr, bs4.element.Tag):
                tds = tr('td')
                ulist.append([tds[0].text.strip(), tds[1].text.strip(), tds[2].text.strip(), tds[3].text.strip()])
    except:
        print('获取Ulist失败')

三、完整代码:

'''
大学生必备网   https://www.dxsbb.com/news/7564.html
自动化专业大学排名  全国第四轮控制科学与工程学科评估结果
作者:腾格里   日期:2021年2月9日16:18:04
'''

import requests
import bs4
from bs4 import BeautifulSoup

def getHTMLText(url):
    try:
        head = {'user-agent':'Mozilla/5.0'}
        r = requests.get(url, headers = head)
        #print(r.status_code)
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print('获取HTML失败')

def fillUnivList(ulist, html):
    try:
        soup = BeautifulSoup(html, 'html.parser')
        for tr in soup.find('tbody').children:
            if isinstance(tr, bs4.element.Tag):
                tds = tr('td')
                ulist.append([tds[0].text.strip(), tds[1].text.strip(), tds[2].text.strip(), tds[3].text.strip()])
    except:
        print('获取Ulist失败')

def printUnivList(ulist, num):
    tplt = '{0:^10}\t{1:^10}\t{2:^12}\t{3:^10}'
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0],u[1],u[2],u[3],chr(12288)))
        
def main():
    unifo = []
    url = 'https://www.dxsbb.com/news/7564.html'
    html = getHTMLText(url)
    fillUnivList(unifo, html)
    printUnivList(unifo, 30+1)#30 univs
main()

输出效果:
在这里插入图片描述
本篇完:如有错误欢迎指出

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值