Python爬虫:证监会行政处罚爬取
在当今信息爆炸的时代,数据的价值日益凸显。爬虫技术作为一种自动化获取网络信息的手段,已经成为数据科学、市场分析、学术研究等领域不可或缺的工具。本文对于证监会行政处罚内容进行爬取并输出到excel中。
·
在当今信息爆炸的时代,数据的价值日益凸显。爬虫技术作为一种自动化获取网络信息的手段,已经成为数据科学、市场分析、学术研究等领域不可或缺的工具。本文对于证监会行政处罚内容进行爬取并输出到excel中。
文章目录
环境准备
在开始之前,确保你的Python环境中已安装以下库:
requests:用于发送HTTP请求。pandas:用于数据处理和保存为Excel文件。concurrent.futures:用于实现多线程,提高爬取效率。
可以通过以下命令安装所需的库:
pip install requests pandas
目标网站分析
本案例的目标网站是中国证监会官网(CSRC),我们需要从该网站抓取特定页面的数据。通过浏览器的开发者工具(F12),我们可以分析出需要请求的URL和必要的HTTP头部信息。
代码实现
1. 导入必要的库
import os
import requests
import pandas as pd
import time
import random
from requests.exceptions import RequestException
2. 创建Session对象
为了减少每次请求时建立和断开连接的开销,我们使用requests.Session()来保持连接。
session = requests.Session()
3. 定义URL和Headers
通过F12查询到的URL和自动生成的文件头信息如下:
url = 'http://www.csrc.gov.cn/searchList/28de6b87eda140cb93de4dd10d11867d'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
# 其他必要的headers...
}
4. 获取总页数
发送POST请求,获取总页数,并计算总页数。
response = session.post(get_url(1), headers=headers)
response.raise_for_status() # 确保请求成功
total = response.json()['data']['total']
total_pages = (total + 9) // 10 + 1 # 计算总页数
5. 多线程爬取数据
为了提高爬取效率,我们使用ThreadPoolExecutor来实现多线程爬取。
df_list = []
for i in range(1, total_pages):
response = get_response(i)
for item in response.json()["data"]["results"]:
df_list.append({
'channelCodeName': item["channelCodeName"],
# 其他字段...
})
6. 保存数据到Excel
将爬取的数据保存到Excel文件中。
df = pd.DataFrame(df_list)
df.to_excel('output3.xlsx', index=False)
完整代码
import os
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
import pandas as pd
import time
import random
from requests.exceptions import RequestException
# 创建一个Session对象, 使用Session对象来保持连接,减少每次请求时建立和断开连接的开销。
session = requests.Session()
# 通过F12查询到
url = 'http://www.csrc.gov.cn/searchList/28de6b87eda140cb93de4dd10d11867d'
# 自动生成的文件头信息
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
# 其他必要的headers...
}
def get_url(page_num):
url = "http://www.csrc.gov.cn/searchList/28de6b87eda140cb93de4dd10d11867d?_isAgg=true&_isJson=true&_pageSize=10&_template=index&_rangeTimeGte=&_channelName=&page={pageNum}"
return url.format(pageNum=page_num)
# 发送POST请求,获取总页数
response = session.post(get_url(1), headers=headers)
response.raise_for_status()# 确保请求成功
# print(response.json())
with open('output.txt', 'w', encoding='utf-8') as file:
json_data = response.json()
file.write(str(json_data))
total = response.json()['data']['total']
total_pages = (total + 9) // 10 + 1 # 计算总页数
print(total_pages)
def get_response(page_num):
try:
# 随机暂停0到3秒之间,模拟真实用户行为
# time.sleep(random.uniform(0, 3))
response = session.post(get_url(page_num), headers=headers)
response.raise_for_status() # 确保请求成功,抛出异常。
return response
except RequestException as e:
response = session.post(get_url(page_num), headers=headers)
response.raise_for_status() # 确保请求成功,抛出异常。
return response
df_list = []
for i in range(1, total_pages):
print(i)
# response = session.post(get_url(i), headers=headers)
response = get_response(i)
for item in response.json()["data"]["results"]:
print(item["channelCodeName"])
# 将每一项添加到DataFrame中
df_list.append({
'channelCodeName': item["channelCodeName"],
'channelId': item["channelId"],
'channelLevels': item["channelLevels"],
'channelName': item["channelName"],
'content': item["content"],
'manuscriptId': item["manuscriptId"],
'publishedTime': item["publishedTime"],
'publishedTimeStr': item["publishedTimeStr"],
'subTitle': item["subTitle"],
'title': item["title"],
'url': item["url"],
'websiteId': item["websiteId"]
})
# 将列表转换为DataFrame
df = pd.DataFrame(df_list)
# 将DataFrame保存到Excel文件中
df.to_excel('output3.xlsx', index=False)
注意事项
- 遵守Robots协议:在爬取数据前,应检查目标网站的Robots协议,确保爬虫行为合法。
- 异常处理:在请求过程中,应添加异常处理机制,确保爬虫的稳定性。
- 用户代理:合理设置User-Agent,模拟浏览器行为,避免被网站识别为爬虫。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)