import csvimport jsonimport requestsimport os class crawler: def __init__(self): pass def save_data(self, data): with open('./高考志愿.csv', encoding='UTF-8', mode='a+', newline='') as f: f_csv = csv.writer(f) f_csv.writerow(data) f.close() def get_data(self): header = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.58' } # 添加表头 head = ['省份', '年份', '学校名称', '专业', '最低录取分', '最低录取名次', '选课要求']# 清除已存在的同名文件 v_file = '高考志愿.csv' if os.path.exists(v_file): os.remove(v_file) print('高考志愿存在,已清除:{}'.format(v_file)) with open('./高考志愿.csv', encoding='utf-8-sig', mode='w', newline='') as f: f_csv = csv.writer(f) f_csv.writerow(head) f.close() s1 = 'https://static-data.gaokao.cn/www/2.0/schoolspecialindex/' s2 = '/33/3/16/' # 表示浙江省 for m in range(2017, 2023, 1): for k in range(1, 7): try: # 99是四川大学的编号 urll = s1 + str(m) + '/' + str(99) + s2 + str(k) + '.json' print(urll) htmll = requests.get(urll, headers=header).text unicode = json.loads(htmll) try: da = unicode["data"] except: break da = da["item"] for w in da: sc = w["min"] # 最低录取分 min_section = w["min_section"] # 最低录取名次 spname = w["spname"] # 专业名称 sp_info = w["sp_info"] # 选课要求 tap = ('四川', m, '四川大学', spname, sc, min_section, sp_info) self.save_data(tap) except: pass
时间: 2025-03-29 14:14:36 浏览: 154
### 高考志愿数据爬虫代码优化
在编写和优化用于抓取高考志愿数据的 Python 爬虫时,可以从多个方面入手提升效率、稳定性和可维护性。以下是针对现有需求的一些改进建议:
#### 1. **提高请求效率**
如果目标网站支持分页或多线程处理,则可以通过批量发送 HTTP 请求减少等待时间。可以利用 `concurrent.futures` 或者异步框架如 `aiohttp` 来实现多线程/协程操作。
```python
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main(urls):
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
task = asyncio.ensure_future(fetch(session, url))
tasks.append(task)
responses = await asyncio.gather(*tasks)
return responses
loop = asyncio.get_event_loop()
data = loop.run_until_complete(main(["https://example.com/page1", "https://example.com/page2"]))
```
此方法能够显著加快对大量 URL 的访问速度[^3]。
---
#### 2. **增强动态内容解析能力**
对于依赖 JavaScript 动态渲染的内容(例如 Ajax 加载),仅依靠 `requests` 可能无法完全满足需求。此时应考虑引入 Selenium 或 Pyppeteer 这样的工具模拟浏览器行为。
```python
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get('https://zhigaokao.example.com')
soup = BeautifulSoup(driver.page_source, 'html.parser')
universities = soup.find_all('div', class_='university-item') # 假设这是大学列表的选择器
for uni in universities:
name = uni.find('h3').text.strip()
location = uni.find('span', {'class': 'location'}).text.strip()
print(f"{name} - {location}")
driver.quit()
```
上述代码片段展示了如何结合 Selenium 和 BeautifulSoup 解析复杂的 HTML 页面结构[^4]。
---
#### 3. **加强异常处理机制**
网络状况不稳定可能导致某些请求失败,因此应在程序中加入完善的错误捕获逻辑以保障稳定性。
```python
import requests
def get_page_content(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
resp = requests.get(url, timeout=10, headers=headers)
resp.raise_for_status() # 如果响应状态码不是2xx则抛出异常
return resp.content.decode('utf-8')
except requests.exceptions.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
```
通过设置超时参数以及自定义 User-Agent 字符串等方式规避潜在的风险因素[^1]。
---
#### 4. **合理存储与预处理数据**
当面对大规模的数据集时,建议先将其保存至本地文件再进一步加工;同时剔除无意义字段降低内存占用率。
```python
import pandas as pd
df = pd.DataFrame(data={
'University Name': ['Tsinghua University'],
'Province': ['Beijing']
})
# 清洗掉不符合条件的数据项
filtered_df = df[(df['Salary'] != '面议')]
filtered_df.to_excel('./output.xlsx', index=False)
print(filtered_df.describe()) # 统计描述信息便于后续分析
```
这里运用 Pandas 库完成了简单的过滤动作并将最终成果导出为 Excel 表格形式[^5]。
---
#### 5. **遵守法律规范和技术伦理**
务必确认所要采集的目标站点允许此类活动,并仔细阅读其 robots.txt 文件规定哪些路径不可被自动化脚本访问。另外注意保护个人隐私资料不外泄。
---
阅读全文
相关推荐



















