真实网址:https://agents.baidu.com/lingjing/experhub/search/list?pageSize=36&pageNo=1&tagId=-99
返回的json数据:{
"errno": 0,
"msg": "success",
"data": {
"total": 36,
"pageNo": 1,
"pageSize": 36,
"plugins": [
{
"name": "零基础学习路径规划",
"description": "你好,请你给出一个主题,我将给你一份完整的学习路径规划",
"logoUrl": "https://now.bdstatic.com/stash/v1/6f672d5/lingjing-fe/07ccbd4/agent-logo/logo-1.png",
"logoText": {
"bgImage": "",
"labelValue": "1",
"color": 0,
"labelType": 2
},
"previewUrl": "https://t6acl8.smartapps.baidu.com",
"appId": "UjRqa5SBZzwvbRH8I06qp19H6OZdzjCR",
"pluginSource": 3,
"useNum": "786492",
"buildType": 1,
"isOwner": null,
"packageStatus": 6,
"dialogueCount": "2030481",
"developerName": "好想出去玩2020",
"isFavorited": false
},
deepseek中输入提示词:
你是一个Python编程专家,完成一个Python脚本编写的任务,具体步骤如下:
在F盘新建一个Excel文件:baiduaiagent20240619.xlsx
请求网址:
https://agents.baidu.com/lingjing/experhub/search/list?pageSize=36&pageNo=1&tagId=-99请求方法:
GET
状态代码:
200 OK
获取网页的响应,这是一个嵌套的json数据;
获取json数据中"data"键的值,然后获取其中"plugins"键的值,这是一个json数据,提取这个json数据中所有的键写入Excel文件的表头 ,提取这个json数据中所有键对应的值写入Excel文件的列 ;
保存Excel文件;
注意:每一步都输出信息到屏幕;
每爬取1页数据后暂停5-9秒;
需要对 JSON 数据进行预处理,将嵌套的字典和列表转换成适合写入 Excel 的格式,比如将嵌套的字典转换为字符串;
在较新的Pandas版本中,append方法已被弃用。我们应该使用pd.concat来代替。
源代码:
import requests
import pandas as pd
import time
import json
# 请求URL
url = "https://agents.baidu.com/lingjing/experhub/search/list?pageSize=36&pageNo=1&tagId=-99"
# 请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
}
# 创建Excel文件
file_path = "F:/baiduaiagent20240619.xlsx"
df = pd.DataFrame()
# 发送GET请求
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
products = data['data']['plugins']
# 提取所有产品的键作为表头
headers = set()
for product in products:
headers.update(product.keys())
# 创建DataFrame并填充数据
for product in products:
product_data = {header: product.get(header, '') for header in headers}
new_data = pd.DataFrame([product_data])
df = pd.concat([df, new_data], ignore_index=True)
print("Data processed.")
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
# 保存Excel文件
df.to_excel(file_path, index=False)
print(f"Data saved to {file_path}")
# 暂停5-9秒
time.sleep(5 + (1 % 5))