水之魂2367

数据采集第二次作业

作业①:爬取中国气象网天气预报

1)代码:

import requests
from lxml import etree
import sqlite3

# 目标城市天气页面对应URL
city_urls = {
    "北京": "http://www.weather.com.cn/weather/101010100.shtml",
    "上海": "http://www.weather.com.cn/weather/101020100.shtml",
    "广州": "http://www.weather.com.cn/weather/101280101.shtml"
}

# 数据库初始化与建表
def init_db():
    conn = sqlite3.connect("weather.db")
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS weather_info (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        city TEXT NOT NULL,
        date TEXT,
        weather TEXT,
        temp_range TEXT,
        wind_info TEXT
    )
    """)
    conn.commit()
    return conn

# 单城市天气数据爬取与入库
def crawl_weather(city_name, url, conn):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    response = requests.get(url, headers=headers)
    response.encoding = "utf-8"
    html = etree.HTML(response.text)
    
    # XPath定位每日天气节点
    day_list = html.xpath('//ul[@class="t clearfix"]/li')
    cursor = conn.cursor()
    
    for day in day_list:
        date = day.xpath('./h1/text()')[0].strip()
        weather = day.xpath('./p[@class="wea"]/text()')[0].strip()
        temp_high = day.xpath('./p[@class="tem"]/span/text()')
        temp_low = day.xpath('./p[@class="tem"]/i/text()')
        temp_range = f"{temp_high[0]}/{temp_low[0]}" if temp_high else temp_low[0]
        wind = day.xpath('./p[@class="win"]/i/text()')[0].strip()
        
        cursor.execute(
            "INSERT INTO weather_info (city, date, weather, temp_range, wind_info) VALUES (?,?,?,?,?)",
            (city_name, date, weather, temp_range, wind)
        )
    conn.commit()

if __name__ == "__main__":
    db_conn = init_db()
    for city, target_url in city_urls.items():
        crawl_weather(city, target_url, db_conn)
        print(f"{city} 7天天气预报爬取完成")
    db_conn.close()
    print("全部城市天气数据已写入数据库")

实验结果:
程序运行后自动生成 weather.db 数据库文件,weather_info 表中存储了 3 个城市共 21 条 7 天预报数据,字段完整、中文无乱码,覆盖城市、日期、天气、温度、风力全部信息。
实验1结果
如图所示成功爬取天气预报信息,数量过多不全部展示

2)心得体会

通过本次天气预报爬取实验,我系统掌握了静态 HTML 页面的 XPath 定位与解析方法,完整走完了「发起请求→解析页面→提取数据→持久化存储」的爬虫全流程。实验中曾遇到中文乱码问题,通过手动指定响应编码为 utf-8 顺利解决,也让我理解了网页编码对数据提取的影响。
同时我也体会到,静态页面爬取的稳定性依赖页面结构,一旦网站改版解析规则就需要同步调整;而数据库存储的方式,相比控制台打印输出更具实用价值,为后续的数据统计、可视化分析打下了基础。

作业②:爬取股票信息

1)代码:

import requests
import sqlite3

# 数据库初始化
def init_db():
    conn = sqlite3.connect("stock.db")
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS stock_info (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        bStockNo TEXT NOT NULL,
        bStockName TEXT NOT NULL,
        bNewPrice REAL,
        bChangePercent REAL,
        bVolume INTEGER
    )
    """)
    conn.commit()
    return conn

# 批量爬取股票行情
def crawl_stock_data(stock_codes, conn):
    code_str = ",".join(stock_codes)
    api_url = f"https://hq.sinajs.cn/list={code_str}"
    
    # 携带Referer请求头,避免接口拦截
    headers = {
        "Referer": "https://finance.sina.com.cn/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    }
    
    response = requests.get(api_url, headers=headers)
    response.encoding = "gbk"
    lines = response.text.strip().split("\n")
    cursor = conn.cursor()
    
    for code, line in zip(stock_codes, lines):
        content = line.split('"')[1]
        fields = content.split(",")
        if len(fields) < 32:
            continue
        
        stock_name = fields[0]
        pre_close = float(fields[2])
        latest_price = float(fields[3])
        change_percent = round((latest_price - pre_close) / pre_close * 100, 2)
        volume = int(float(fields[8]))
        
        cursor.execute("""
        INSERT INTO stock_info (bStockNo, bStockName, bNewPrice, bChangePercent, bVolume)
        VALUES (?,?,?,?,?)
        """, (code[2:], stock_name, latest_price, change_percent, volume))
    
    conn.commit()

if __name__ == "__main__":
    # 5只样本股票代码
    stock_list = ["sh600519", "sz000001", "sz300750", "sh601318", "sz002594"]
    db_conn = init_db()
    crawl_stock_data(stock_list, db_conn)
    db_conn.close()
    print("股票行情数据爬取完成,已全部写入数据库")

实验结果:
程序成功请求接口并解析 5 只股票的实时行情,所有字段计算准确、数据完整写入 stock.db 数据库;通过添加 Referer 请求头绕过了接口的来源校验,保证了数据获取的稳定性。

实验2结果

2)心得体会

本次实验让我掌握了接口型数据的爬取思路,相比于 HTML 页面解析,API 接口返回的结构化数据解析效率更高、容错性更强。通过浏览器 F12 抓包找接口的过程,也让我理解了前后端分离网站的数据加载逻辑。
实验中我深刻体会到请求头的重要性,很多接口都会校验 Referer、User-Agent 等字段,模拟浏览器请求头是爬虫的必备技巧。同时金融数据对时效性要求高,接口爬取的方式更适合高频采集场景,数据库持久化也为后续的行情统计、趋势分析提供了数据基础。

作业③:爬取中国大学2021主榜所有院校信息

1)代码:

import requests
import sqlite3

# 数据库初始化
def init_db():
    conn = sqlite3.connect("university.db")
    cursor = conn.cursor()
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS university_rank (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        rank_num TEXT,
        school_name TEXT,
        province TEXT,
        school_type TEXT,
        total_score REAL
    )
    """)
    conn.commit()
    return conn

# 爬取大学排名数据
def crawl_university_rank(conn):
    api_url = "https://www.shanghairanking.cn/api/pub/v1/bcur?bcur_type=11&year=2021"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Referer": "https://www.shanghairanking.cn/"
    }
    
    response = requests.get(api_url, headers=headers)
    json_data = response.json()
    rank_list = json_data["data"]["rankings"]
    cursor = conn.cursor()
    
    for item in rank_list:
        rank = item["rankOverall"]
        name = item["univNameCn"]
        province = item["province"]
        univ_type = item["univCategory"]
        score = item["score"]
        
        cursor.execute("""
        INSERT INTO university_rank (rank_num, school_name, province, school_type, total_score)
        VALUES (?,?,?,?,?)
        """, (rank, name, province, univ_type, score))
    
    conn.commit()

if __name__ == "__main__":
    db_conn = init_db()
    crawl_university_rank(db_conn)
    db_conn.close()
    print("2021中国大学排名数据爬取完成,已写入数据库")

实验结果:
成功爬取 2021 软科中国大学主榜全部院校数据,排名、校名、省市、类型、总分 5 个字段完整准确,全部写入 university.db 数据库;接口方式爬取数据效率高、容错性强,不受页面样式改版影响。

实验3结果
内容过多不全部展示

2)心得体会

通过本次实验,我真正掌握了浏览器 F12 抓包的核心技能,也深刻理解了「找数据接口比写页面解析更重要」的爬虫思路。前后端分离的网站中,数据通过接口独立加载,直接请求接口不仅代码更简洁,数据完整性和稳定性也远高于 HTML 解析。
实验中我也遇到了接口的来源校验问题,通过添加 Referer 请求头顺利解决,进一步巩固了请求头模拟的知识点。这次实验让我明白,爬虫不是机械地堆砌解析规则,而是要先分析网站的数据加载逻辑,找到最优的数据获取路径,才能写出高效、稳定的爬虫程序。

posted on 2026-11-17 16:46  水之魂2367  阅读(7)  评论(0)    收藏  举报

导航