python——实例:中国大学排名定向爬虫

import requests
import bs4

# 获取网页内容
def get_html(url):
    response = requests.get(
        url=url,
        headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'
        }
    )
    response.encoding = response.apparent_encoding
    html_text = response.text
    return html_text

# 提取有用数据到恰当的数据结构中
def parse_html(html_text, n):
    soup = bs4.BeautifulSoup(html_text, "html.parser")
    table = soup.select("table[class='rk-table']")[0]
    tbody = table.select("tbody")[0]
    rows = tbody.find_all("tr")
    data = []
    for row in rows:
        cols = row.find_all("td")
        rank = int(cols[0].get_text().strip())
        if rank <= n: # 仅处理前 n 名
            name = cols[1].select_one("div.univname div:nth-child(1) a").get_text().strip()
            level = cols[2].get_text().strip()
            score = cols[3].get_text().strip()
            total_score = cols[4].get_text().strip()
            educational_level = cols[5].get_text().strip()
            data.append([rank, name, level, score, total_score, educational_level])
        else:
            break
    return data

# 将数据打印输出
def print_data(data):
    print("{:<5s}{:<13s}{:<10s}{:<10s}{:<10s}{:<10s}".format('排名', '学校名称', '类型', '总分', '省市', '办学层次'))
    for item in data:
        print("{:<5d}{:<13s}{:<10s}{:<10s}{:<10s}{:<10s}".format(item[0], item[1], item[2], item[3], item[4], item[5]))

# 主函数
def main(n):
    # 从网络上获取网页内容
    url = "https://www.shanghairanking.cn/rankings/bcur/2023"
    html_text = get_html(url)

    # 分析网页内容并提取有用数据到恰当的数据结构中
    data = parse_html(html_text, n)

    # 将数据打印输出
    print_data(data)

if __name__ == '__main__':
    main(10)

python——实例:中国大学排名定向爬虫_第1张图片

 

你可能感兴趣的:(python,爬虫,开发语言)