python从网页抓取数据

import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        # 这里以提取所有链接为例
        links = soup.find_all('a')
        for link in links:
            print(link.get('href'))
    except requests.RequestException as e:
        print(f"请求网页时发生错误: {e}")
    except Exception as e:
        print(f"发生了一个未知错误: {e}")


if __name__ == "__main__":
    url = "https://example.com"  # 替换为实际网页 URL
    scrape_website(url)

分析 CSV 文件中的数据

import csv

def analyze_csv_file(file_path, column_index):
    try:
        values = []
        with open(file_path, 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            next(reader)  # 跳过标题行
            for row in reader:
                try:
                    value = float(row[column_index])
                    values.append(value)
                except (IndexError, ValueError):
                    continue
        if values:
            average = sum(values) / len(values)
            max_value = max(values)
            min_value = min(values)
            print(f"平均值: {average}")
            print(f"最大值: {max_value}")
            print(f"最小值: {min_value}")
        else:
            print("未找到有效的数值数据。")
    except FileNotFoundError:
        print("错误: 指定的 CSV 文件未找到!")
    except Exception as e:
        print(f"错误: 发生了一个未知错误: {e}")


if __name__ == "__main__":
    file_path = "your_file.csv"  # 替换为实际 CSV 文件路径
    column_index = 0  # 替换为要分析的列索引
    analyze_csv_file(file_path, column_index)

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万能小贤哥

感谢大捞

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值