# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import bs4 def getHTMLText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" def fillUnivList(ulist, html): soup = BeautifulSoup(html, "html.parser") for tr in soup.find('tbody').children: # 先检索到tbody标签 if isinstance(tr, bs4.element.Tag): tds = tr('td') # 查询tr中的td标签,等价于tr.find_all('td') # 新版的排名封装在a标签中,所以这里需要具体到查找属性为'name-cn'的a标签并存储其字符串,即大学的中文名称 a = tr('a','name-cn') ulist.append([tds[0].string.strip(),a[0].string.strip(),tds[2].text.strip(),tds[4].string.strip()]) # 使用二维列表存储信息 def printUnivList(ulist, num): tplt = "{0:^10}\t{1:{4}^10}\t{2:^10}\t{3:^10}" # {3}表示需要填充时使用format的第三个变量进行填充,即使用中文空格 print(tplt.format("排名", "学校名称", "地区", "总分", chr(12288))) for i in range(num): u = ulist[i] print(tplt.format(u[0], u[1], u[2], u[3], chr(12288))) def main(): uinfo = [] url = "https://www.shanghairanking.cn/rankings/bcur/2021" html = getHTMLText(url) fillUnivList(uinfo, html) printUnivList(uinfo, 20) # 20 univ if __name__ == "__main__": main()
时间: 2024-04-26 20:25:06 浏览: 157
这段代码使用了 requests 库和 BeautifulSoup 库,爬取了“2021上海交通大学世界大学学术排名(本科)”页面的数据,并输出前20个大学的排名、学校名称、地区和总分四个信息。
代码的主要流程如下:
1. 定义了一个 getHTMLText(url) 函数,用于发送 HTTP 请求获取指定 URL 页面的 HTML 源代码,并返回源代码的字符串形式。
2. 定义了一个 fillUnivList(ulist, html) 函数,用于解析 HTML 代码,提取出表格中的信息(包括排名、学校名称、地区和总分),并将信息存储到二维列表 ulist 中。
3. 定义了一个 printUnivList(ulist, num) 函数,用于按照一定格式输出 ulist 中的排名、学校名称、地区和总分信息。其中使用了 {0:^10}、{1:{4}^10}、{2:^10}、{3:^10} 四个占位符,用于控制输出的格式,chr(12288) 表示中文空格。
4. 在 main() 函数中,定义了一个空列表 uinfo 和一个目标 URL,先调用 getHTMLText(url) 函数获取页面的 HTML 源代码,再调用 fillUnivList(uinfo, html) 函数解析 HTML 代码,并将信息存储到 uinfo 中。最后调用 printUnivList(uinfo, 20) 函数输出前20个大学的信息。
需要注意的是,这里使用了一个列表推导式 a = tr('a','name-cn'),其作用是从 tr 标签中查询属性为 'name-cn' 的 a 标签,并将查询结果存储到列表 a 中。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)