当前位置: 首页 > news >正文

python爬虫实践

两个python程序的小实验(附带源码)

题目1

爬取http://www.gaosan.com/gaokao/196075.html 中国大学排名,并输出。提示:使用requests库获取页面的基本操作获取该页面,运用BeautifulSoup解析该页面绑定对象soup,soup.title, soup.string, soup.get_text()。pd.DataFrame创建二维数据。
在这里插入图片描述


\# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import bs4def getHTMLText(url):try:r = requests.get(url, timeout=30)r.raise_for_status()r.encoding = r.apparent_encodingreturn r.textexcept: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 univif __name__ == "__main__":main()
题目2:

从新闻中爬取NBA“西部球队”排名。https://nba.hupu.com/standings

如下图输出:
在这里插入图片描述

import requests
from bs4 import BeautifulSoupurl = "https://nba.hupu.com/standings"
response = requests.get(url)
\# 打印响应内容,用于检查是否正确获取了网页数据
print(response.text)
soup = BeautifulSoup(response.text, "html.parser")\# 确保找到的table不是None
table = soup.find("table", class_="players_table")  # 注意这里使用了class_,因为class是Python关键字
if table is None:print("没有找到class为rank-table的table,请检查网页结构或选择器是否正确。")
else:rows = table.find_all("tr")for row in rows:cells = row.find_all("td")if cells:  # 确保td元素存在才进行处理print(' '.join(cell.text.strip() for cell in cells if cell.text.strip()))print(' '.join(cell.text.strip() for cell in cells if cell.text.strip()))
http://www.lryc.cn/news/414907.html

相关文章:

  • 【前端面试】七、算法-数组展平
  • Laravel php框架与Yii php 框架的优缺点
  • 使用 addRouteMiddleware 动态添加中间
  • Zookeeper未授权访问漏洞
  • 【JavaEE】定时器
  • 2024带你轻松玩转Parallels Desktop19虚拟机!让你在Mac电脑上运行Windows系统
  • 【算法】递归实现二分查找(优化)以及非递归实现二分查找
  • CDN 是什么?
  • 索引:SpringCloudAlibaba分布式组件全部框架笔记
  • 2024第五届华数杯数学建模竞赛C题思路+代码
  • FFmpeg源码:av_reduce函数分析
  • nginx: [error] open() “/run/nginx.pid“ failed (2: No such file or directory)
  • <数据集>BDD100K人车识别数据集<目标检测>
  • 利用SSE打造极简web聊天室
  • 代码随想录第二十天|动态规划(4)
  • TreeSize:免费的磁盘清理与管理神器,解决C盘爆满的燃眉之急
  • 如何建立自己的技术知识体系
  • JS优化了4个自定义倒计时
  • 模型实战(25)之 基于LoFTR深度学习匹配算法实现图像拼接
  • 计算机毕业设计Python+Spark知识图谱高考志愿推荐系统 高考数据分析 高考可视化 高考大数据 大数据毕业设计
  • 【python】文件
  • 《Attention Is All You Need》核心观点及概念
  • 【中项】系统集成项目管理工程师-第9章 项目管理概论-9.9价值交付系统
  • JS+H5美观的带搜索的博客文章列表(可搜索多个参数)
  • 牛客周赛 Round 54 (c++题解)
  • htsjdk库Genotype及相关类介绍
  • C++ 最短路(spfa) 洛谷
  • MySQL的数据类型
  • xss漏洞(四,xss常见类型)
  • 繁简之争:为什么手机芯片都是 ARM