项目名称:学号_京东笔记本数据分析 爬虫部分 ```python import requests from bs4 import BeautifulSoup import pymongo import re # MongoDB连接 client = pymongo.MongoClient('mongodb://localhost:27017/') db = client['学号_京东笔记本数据'] collection = db['notebooks'] def get_product_info(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') products = [] items = soup.find_all('li', class_='gl-item') for item in items: name = item.find('div', class_='p-name').a.em.text.strip() price = item.find('strong', class_='J_price').i.text.strip() shop = item.find('a', class_='curr-shop').text.strip() comments = item.find('a', class_='J_comment').text.strip() # 数据清洗 price = float(re.sub(r'[^\d.]', '', price)) comments = int(re.sub(r'\D', '', comments)) product = { 'name': name, 'price': price, 'shop': shop, 'comments': comments } products.append(product) return products def save_to_mongodb(products): collection.insert_many(products) def main(): url = 'https://search.jd.com/Search?keyword=笔记本&enc=utf-8' products = get_product_info(url) save_to_mongodb(products) print(f'已爬取 {len(products)} 条数据并保存到 MongoDB') if __name__ == '__main__': main() ``` 数据分析部分 ```python import pandas as pd import matplotlib.pyplot as plt # 连接 MongoDB client = pymongo.MongoClient('mongodb://localhost:27017/') db = client['学号_京东笔记本数据'] collection = db['notebooks'] # 读取数据 data = list(collection.find()) df = pd.DataFrame(data) # 数据预处理 df['price'] = df['price'].astype(float) df['comments'] = df['comments'].astype(int) # 价格分布直方图 plt.figure(figsize=(10, 6)) plt.hist(df['price'], bins=30, edgecolor='black') plt.title('笔记本价格分布') plt.xlabel('价格') plt.ylabel('数量') plt.text(0.95, 0.95, f'总样本数: {len(df)}', ha='right', va='top', transform=plt.gca().transAxes) plt.show() # 联想笔记本分析 lenovo_df = df[df['name'].str.contains('联想')] model_sales = lenovo_df.groupby('name')['comments'].sum().sort_values(ascending=False) model_prices = lenovo_df.groupby('name')['price'].mean() # 销售量柱状图 plt.figure(figsize=(12, 6)) model_sales.plot(kind='bar') plt.title('联想笔记本销售量') plt.xlabel('型号') plt.ylabel('销量') for i, v in enumerate(model_sales): plt.text(i, v + 10, str(v), ha='center', va='bottom') plt.show() # 均价柱状图 plt.figure(figsize=(12, 6)) model_prices.plot(kind='bar', color='skyblue') plt.title('联想笔记本均价') plt.xlabel('型号') plt.ylabel('均价') for i, v in enumerate(model_prices): plt.text(i, v + 10, f'{v:.2f}', ha='center', va='bottom') plt.show() ``` 需要注意的逻辑点: 1. 反爬虫机制:京东网站有反爬虫机制,频繁请求可能会被封 IP。可以考虑使用代理 IP 或者设置合理的请求间隔时间。 2. 数据清洗:在爬取数据时,商品名、价格、店铺名、评价数等字段可能包含特殊字符或空格,需要进行适当的清洗处理。 3. 异常处理:在爬取和处理数据时,可能会遇到网络请求失败、解析错误等情况,建议添加异常处理机制,确保程序的健壮性。 [2024-12-12 00:20:07 | AI写代码神器 | 968点数解答]