python爬虫实践

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

题目1

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

python 复制代码
\# -*- 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()
题目2:

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

如下图输出:

python 复制代码
import requests
from bs4 import BeautifulSoup

url = "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()))
相关推荐
珊瑚里的鱼2 分钟前
C++14 和 C++17 的核心新特性
开发语言·c++
RSTJ_16252 分钟前
PYTHON+AI LLM DAY SEVENTY
人工智能·python·深度学习
techdashen4 分钟前
深入理解 Rust Futures:从零开始,一头扎到底
开发语言·后端·rust
财经资讯数据_灵砚智能6 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月8日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
程序猿乐锅10 分钟前
【JAVASE | 第十六篇】多线程
java·开发语言
m沐沐12 分钟前
数据集的六种填充方法——下(使用众数填充+使用逻辑回归填充+使用随机森林填充)
python·随机森林·机器学习·pycharm·逻辑回归
TonyLee01712 分钟前
AutoDL租卡记录
服务器·python
m沐沐13 分钟前
【机器学习】7 种分类模型实战(逻辑回归→随机森林→SVM→AdaBoost→朴素贝叶斯→XGBoost→神经网络)
人工智能·pytorch·python·随机森林·机器学习·分类·逻辑回归
布局呆星16 分钟前
Spring Boot + JWT + Spring Security 认证授权实战:双角色、双 Token、方法级权限,一次讲透
java·开发语言
csdndeyeye16 分钟前
从Ctrl+C/V到一键填充:AI投简历工具实测
c语言·开发语言·自动化·秋招·ai助手·网申·ai投简历