python1.爬取主流电商平台的华为手机的销售数据,将数据保存在自己姓名.txt中 2.分析数据,并图形化输出
时间: 2024-04-05 22:33:39 浏览: 183
Sure, I can help you with that. To crawl sales data for Huawei smartphones from popular e-commerce platforms and save it to a file named after your name, you can follow these steps:
1. Import the necessary libraries:
```python
import requests
import json
```
2. Define a function to crawl the sales data from the e-commerce platform. Here's an example using JD.com (you can modify it for other platforms):
```python
def crawl_sales_data():
url = "https://api.jd.com/routerjson"
# Construct the request payload
payload = {
"method": "jd.union.open.goods.promotiongoodsinfo.query",
"app_key": "your_app_key",
"v": "1.0",
"param_json": {
"goodsReqDTO": {
"eliteId": "1",
"pageIndex": "1",
"pageSize": "100",
"sortName": "inOrderCount30DaysSku",
"sort": "desc",
"brandCode": "huawei",
"categoryId": "",
"owner": "pop"
}
}
}
# Send the request
response = requests.post(url, json=payload)
# Process the response
if response.status_code == 200:
data = json.loads(response.text)
# Extract and save the sales data
with open("your_name.txt", "w") as file:
for item in data["result"]["data"]:
file.write(f"Product Name: {item['skuName']}, Sales: {item['inOrderCount30DaysSku']}\n")
print("Sales data saved successfully!")
else:
print("Failed to retrieve sales data!")
```
Note: You need to obtain your own app key from JD.com's developer platform and replace `"your_app_key"` with it.
3. Call the `crawl_sales_data()` function to crawl and save the sales data:
```python
crawl_sales_data()
```
To analyze the data and visualize it, you can use libraries like pandas and matplotlib. Here's an example of how to do it:
1. Import the necessary libraries:
```python
import pandas as pd
import matplotlib.pyplot as plt
```
2. Read the saved sales data from the file:
```python
df = pd.read_csv("your_name.txt", delimiter=",", names=["Product Name", "Sales"])
```
3. Analyze the data:
```python
# Get total sales
total_sales = df["Sales"].sum()
# Get top 5 products by sales
top_products = df.nlargest(5, "Sales")
# Get average sales
average_sales = df["Sales"].mean()
```
4. Visualize the data:
```python
# Plot a bar chart of top products by sales
plt.bar(top_products["Product Name"], top_products["Sales"])
plt.xlabel("Product")
plt.ylabel("Sales")
plt.title("Top 5 Products by Sales")
plt.xticks(rotation=45)
plt.show()
# Display total sales and average sales
print("Total Sales:", total_sales)
print("Average Sales:", average_sales)
```
Remember to replace `"your_name.txt"` with the actual filename you used to save the data.
I hope this helps you get started with crawling and analyzing sales data for Huawei smartphones from e-commerce platforms! Let me know if you have any further questions.
阅读全文