Beautiful Soup 是一个用于解析HTML和XML文档的库,非常适用于网页爬虫和数据抓取。可以提取所需信息,无需手动分析网页源代码,简化了从网页中提取数据的过程,使得数据抽取变得更加容易。
应用场景
功能特点
基本用法
解析器初始化: 通过将HTML文档传递给Beautiful Soup来创建解析器对象。
from bs4 import BeautifulSoup# 从文件中读取HTMLwith open("example.html", "r") as file: soup = BeautifulSoup(file, "html.parser")
遍历文档树: 可以使用标签名称、类名、id等属性进行文档元素的遍历和搜索。
x# 通过标签名获取元素title = soup.title
# 通过类名获取元素important_texts = soup.find_all("p", class_="important")
# 通过id获取元素content = soup.find(id="content")
提取数据: 可以获取元素的文本内容、属性等信息。
xxxxxxxxxx# 获取文本内容print(title.text)
# 获取属性值print(content["href"])
修改文档树: 可以添加、删除或修改文档中的标签和内容。
xxxxxxxxxx# 创建新的标签new_tag = soup.new_tag("a", href="http://example.com")new_tag.string = "Link Text"
# 在文档中插入新标签content.append(new_tag)
需要与网络交互时,Requests库是不可或缺。Requests简化了与目标网站接口的通信,易于使用且功能强大,支持多种HTTP方法和参数设置,能够轻松发送HTTP请求并处理响应。网络爬虫、API调用或是测试网站,Requests都能够让这些任务变得轻而易举。
在企业数据采购中,经常需要与供应商或合作伙伴的API进行数据交换。使用requests库可以轻松实现数据的发送和接收,无论是从外部API获取数据还是向外部API推送数据,都可以通过requests来完成。
Requests库特点
基本用法
xxxxxxxxxx# API数据获取import requests
response = requests.get('https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key')if response.status_code == 200: weather_data = response.json() # 处理数据逻辑
# Web数据抓取 import requestsfrom bs4 import BeautifulSoup
response = requests.get('https://example.com')if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') # 提取所需数据信息xxxxxxxxxximport requests
payload = {'key1': 'value1', 'key2': 'value2'}headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_TOKEN'}
response = requests.post('https://api.example.com/endpoint', json=payload, headers=headers)if response.status_code == 201: # 处理成功发送数据后的响应xxxxxxxxxximport requests
try: response = requests.get('https://api.example.com/data') response.raise_for_status() # 如果响应状态码不是200,则会抛出HTTPError异常 data = response.json() # 处理数据except requests.HTTPError as http_err: print(f'HTTP error occurred: {http_err}')except Exception as err: print(f'Other error occurred: {err}')xxxxxxxxxxwith requests.Session() as session: session.get('https://example.com/login', auth=('user', 'pass')) # 保持登录状态进行后续请求 response = session.get('https://example.com/dashboard')xxxxxxxxxx# Token认证:使用请求头中的Token进行认证headers = {'Authorization': 'Bearer YOUR_TOKEN'}
# Basic Auth:通过提供用户名和密码进行基本认证。auth = ('username', 'password')response = requests.get('https://api.example.com/data', auth=auth)xxxxxxxxxximport requestsimport logging
logging.basicConfig(filename='requests.log', level=logging.INFO)
try: response = requests.get('https://api.example.com/data') response.raise_for_status() logging.info('Request successful')except requests.HTTPError as http_err: logging.error(f'HTTP error occurred: {http_err}')except Exception as err: logging.error(f'Other error occurred: {err}')
| 特点 | Beautiful Soup | Requests |
|---|---|---|
| 主要功能 | 解析HTML和XML文档,提取数据 | 发送HTTP请求,处理响应 |
| 用途 | 网页解析、数据抽取和处理 | 向服务器发起HTTP请求、处理响应,获取网络数据 |
| 关注重点 | 文档解析、数据提取 | HTTP请求和响应的处理 |
| 主要特点 | - 提供多种解析器 - 方便的API来遍历文档树、搜索元素、提取数据 - 修复HTML不完整标签 | - 提供简洁的API - 支持多种HTTP方法 - 处理认证、Cookie、SSL验证等 |
| 适用场景 | 从网页中提取特定数据、数据清洗、提取链接等 | 发送HTTP请求、获取网页内容、与API进行交互 |
Jupyter Notebook是一个开源的交互式笔记本环境,支持多种编程语言,最常用的是Python。它以网页的形式提供一个交互式界面,允许用户在浏览器中编写和运行代码、展示文本、图像、公式等内容,并保存成为具有可执行代码、可视化结果和解释性文档的笔记本。Jupyter Notebook是数据科学家和研究人员的最爱,无论是在进行数据分析、机器学习建模还是原型设计,Jupyter Notebook都是无可替代的工具。
Jupyter Notebook作为一个灵活、交互式、功能丰富的工具,为数据科学家、教育工作者和开发人员提供了一个方便的平台,可以方便地探索数据、编写文档和演示成果。
主要特点和功能
用途和应用场景
使用方法
jupyter notebook,会在浏览器中打开Jupyter界面。
NumPy是Python中用于科学计算的一个强大的库,主要用于处理数组和矩阵运算。它提供了丰富的功能和高效的数据结构,是许多科学和工程领域中常用的核心库之一。
主要特点和功能
ndarray对象,用于表示多维数组,可以进行高效的数值运算。用途和应用场景
NumPy使用介绍可见另一篇博客文章:https://blog.csdn.net/wt334502157/article/details/128185332
Pandas是Python中用于数据处理和分析的强大库,它建立在NumPy的基础上,提供了更高级的数据结构和工具,使得数据操作更加便捷和高效。Pandas通常用于处理结构化数据,比如表格数据、时间序列等,无论是需要进行数据清洗、转换还是统计分析,Pandas都可以帮助您快速达成目标
主要特点和功能
DataFrame对象,类似于电子表格或SQL数据库中的表格,用于处理二维数据。Series对象,类似于一维数组或列表,用于处理一维数据。用途和应用场景
Pandas使用介绍可见另一篇博客文章:https://blog.csdn.net/wt334502157/article/details/128219770
Matplotlib是Python中用于绘制图表和可视化数据的库,是Python中最常用的数据可视化库之一,无论是在制作科学图表、数据可视化还是报告,都具有高度的可定制性,Matplotlib提供了丰富的绘图选项,可以让数据以最吸引人的方式呈现。
主要特点和功能
用途和应用场景
基本用法示例
xxxxxxxxxximport matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]
plt.plot(x, y)plt.xlabel('X Axis')plt.ylabel('Y Axis')plt.title('Line Chart')plt.show()
xxxxxxxxxximport matplotlib.pyplot as plt
x = ['板甲', '锁甲', '皮甲', '布甲']y = [30, 12, 37, 26]
plt.bar(x, y)plt.xlabel('装备类型')plt.ylabel('玩家占比')plt.title('各甲玩家占比')# Windows 设置显示中文plt.rcParams['font.sans-serif'] = 'SimHei'plt.show()
xxxxxxxxxximport matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]y = [2, 2, 6, 9, 16]
plt.scatter(x, y)plt.xlabel('X Axis')plt.ylabel('Y Axis')plt.title('Scatter Plot')plt.show()
xxxxxxxxxximport numpy as npimport matplotlib.pyplot as plt# 创建figurefig = plt.figure(dpi=120)# 准备好极坐标系的数据# 半径为[0,1]r = np.arange(0, 1, 0.001)theta = 2 * 2*np.pi * r# 极坐标下绘制line, = plt.polar(theta, r, color='#ee8d18', lw=3)plt.show()
Seaborn是建立在Matplotlib之上的数据可视化库,专注于创建具有统计意义的各种图表。它提供了简单的高级接口,可以轻松地创建漂亮的统计图表,并且具有更好的默认设置,使得数据可视化变得更加简单和直观。
Seaborn提供了一些Matplotlib不提供或不易实现的高级图表类型,如小提琴图、热图、分布图等,这些图表类型能更好地展示数据的分布、关系和特征;具有更好看的默认主题和调色板,使得图表外观更为美观,无需额外调整,让用户在默认情况下就能得到具有吸引力的图表。
虽然Seaborn更加强大,但并不是取代Matplotlib,而是在Matplotlib的基础上提供了更多的功能和便利性,特别适用于统计分析、数据探索和一些高级的可视化需求。在实际应用中,它们可以结合使用,根据不同的需求选择合适的库来绘制图表。
主要特点和功能:
用途和应用场景:
基本用法示例:
绘制箱线图:
xxxxxxxxxximport seaborn as snsimport matplotlib.pyplot as plt
# 加载示例数据集tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)plt.xlabel('日期')plt.ylabel('账单')plt.title('每日总账单方框图')# Windows 设置显示中文plt.rcParams['font.sans-serif'] = 'SimHei'plt.show()
xxxxxxxxxximport seaborn as snsimport matplotlib.pyplot as plt
# 加载示例数据集tips = sns.load_dataset("tips")
sns.violinplot(x="day", y="total_bill", data=tips)plt.xlabel('日期')plt.ylabel('账单')plt.title('每日总账单小提琴图图')# Windows 设置显示中文plt.rcParams['font.sans-serif'] = 'SimHei'plt.show()
xxxxxxxxxximport seaborn as snsimport matplotlib.pyplot as plt
# 创建一个矩阵数据data = sns.load_dataset("flights").pivot("month", "year", "passengers")
sns.heatmap(data, annot=True, fmt="d", cmap="YlGnBu")plt.xlabel('年')plt.ylabel('月')plt.title('航班乘客热呈图')plt.show()
scikit-learn(sklearn)是一个用于机器学习和数据挖掘的Python库,提供了各种机器学习算法实现和简单而有效的工具,用于数据挖掘和数据分析。它建立在NumPy、SciPy和Matplotlib之上,包含了各种机器学习算法和工具,适用于各种机器学习任务。
常见的机器学习任务
基本用法示例
xxxxxxxxxxfrom sklearn.linear_model import LinearRegressionfrom sklearn.datasets import make_regressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorimport matplotlib.pyplot as plt
# 设置中文字体以支持中文显示plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False
# 生成随机回归数据集X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
# 划分数据集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建线性回归模型并拟合数据model = LinearRegression()model.fit(X_train, y_train)
# 预测并评估模型y_pred = model.predict(X_test)mse = mean_squared_error(y_test, y_pred)print("均方误差:", mse)
# 可视化结果plt.scatter(X_test, y_test, color='black')plt.plot(X_test, y_pred, color='blue', linewidth=3)plt.xlabel('X')plt.ylabel('y')plt.title('线性回归')plt.show()
xxxxxxxxxxfrom sklearn.datasets import make_blobsfrom sklearn.cluster import KMeansimport matplotlib.pyplot as plt
# 设置中文字体以支持中文显示plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False
# 生成随机聚类数据X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=42)
# 构建并拟合K-Means模型kmeans = KMeans(n_clusters=4)kmeans.fit(X)
# 可视化聚类结果plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red', marker='*', label='聚类中心')plt.title('K-Means聚类')plt.legend()plt.show()
xxxxxxxxxxfrom sklearn.datasets import load_irisfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.tree import plot_tree
# 设置中文字体以支持中文显示plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False
# 加载鸢尾花数据集iris = load_iris()X, y = iris.data, iris.target
# 划分数据集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 构建并拟合决策树模型clf = DecisionTreeClassifier(max_depth=3, random_state=42)clf.fit(X_train, y_train)
# 预测并评估模型y_pred = clf.predict(X_test)accuracy = accuracy_score(y_test, y_pred)print("准确率:", accuracy)
# 可视化决策树plt.figure(figsize=(12, 8))plot_tree(clf, feature_names=iris.feature_names, class_names=iris.target_names, filled=True)plt.show()
假设我们想要根据企业的注册资本、成立年份、行业等信息来预测企业的年营业额。以下是一个简化的示例
xxxxxxxxxximport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_errorimport matplotlib.pyplot as pltimport numpy as np
# 设置中文字体以支持中文显示plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False
# 手动生成示例数据(假设这是一个简化的数据集)np.random.seed(42)data = { '注册资本': np.random.randint(100, 1000, 50), '成立年份': np.random.randint(2000, 2020, 50), '行业': np.random.choice(['制造业', '服务业', '零售业'], 50), '年营业额': np.random.randint(100000, 1000000, 50)}
# 创建DataFramedf = pd.DataFrame(data)
# 对行业进行独热编码df = pd.get_dummies(df, columns=['行业'])
# 数据预处理,选择特征和目标值X = df[['注册资本', '成立年份', '行业_制造业', '行业_服务业', '行业_零售业']]y = df['年营业额']
# 划分数据集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建线性回归模型并拟合数据model = LinearRegression()model.fit(X_train, y_train)
# 预测并评估模型y_pred = model.predict(X_test)mse = mean_squared_error(y_test, y_pred)print("均方误差:", mse)
# 可视化结果(展示预测值和实际值的对比)plt.figure(figsize=(8, 6))plt.plot(range(len(y_pred)), y_pred, label='预测年营业额', marker='o')plt.plot(range(len(y_test)), y_test, label='实际年营业额', marker='x')plt.xlabel('样本编号')plt.ylabel('年营业额')plt.title('年营业额预测结果')plt.legend()plt.show()
Keras 是一个高层神经网络 API,它可以运行在 TensorFlow、Theano 和 Microsoft Cognitive Toolkit(CNTK)之上,使得深度学习任务更加简单和快速。它设计用来快速试验和搭建神经网络模型,具有易用性和灵活性。
以下是一个简单的示例,展示了如何使用 Keras 来构建一个简单的全连接神经网络,并训练一个分类模型:
xxxxxxxxxximport kerasfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.optimizers import Adamfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_split
# 生成分类数据X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
# 划分数据集X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建模型model = Sequential()model.add(Dense(64, input_shape=(20,), activation='relu'))model.add(Dense(32, activation='relu'))model.add(Dense(1, activation='sigmoid'))
# 编译模型model.compile(optimizer=Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型history = model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_test, y_test))
# 可视化训练过程import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='训练准确率')plt.plot(history.history['val_accuracy'], label='验证准确率')plt.xlabel('Epochs')plt.ylabel('准确率')plt.legend()plt.show()
/**Epoch 1/1025/25 [====================] - 0s 6ms/step - loss: 0.6231 - accuracy: 0.6900 - val_loss: 0.5630 - val_accuracy: 0.7400Epoch 2/1025/25 [====================] - 0s 2ms/step - loss: 0.4710 - accuracy: 0.8525 - val_loss: 0.4817 - val_accuracy: 0.7850Epoch 3/1025/25 [====================] - 0s 2ms/step - loss: 0.3752 - accuracy: 0.8763 - val_loss: 0.4277 - val_accuracy: 0.8150Epoch 4/1025/25 [====================] - 0s 2ms/step - loss: 0.3247 - accuracy: 0.8925 - val_loss: 0.4103 - val_accuracy: 0.8300Epoch 5/1025/25 [====================] - 0s 2ms/step - loss: 0.2992 - accuracy: 0.8950 - val_loss: 0.4085 - val_accuracy: 0.8300Epoch 6/1025/25 [====================] - 0s 2ms/step - loss: 0.2821 - accuracy: 0.9025 - val_loss: 0.4048 - val_accuracy: 0.8400Epoch 7/1025/25 [====================] - 0s 2ms/step - loss: 0.2696 - accuracy: 0.9038 - val_loss: 0.3964 - val_accuracy: 0.8400Epoch 8/1025/25 [====================] - 0s 2ms/step - loss: 0.2598 - accuracy: 0.9025 - val_loss: 0.4061 - val_accuracy: 0.8400Epoch 9/1025/25 [====================] - 0s 2ms/step - loss: 0.2484 - accuracy: 0.9150 - val_loss: 0.4035 - val_accuracy: 0.8350Epoch 10/1025/25 [====================] - 0s 2ms/step - loss: 0.2383 - accuracy: 0.9125 - val_loss: 0.4063 - val_accuracy: 0.8550**/