You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决API访问时的406不可接受错误?(BeautifulSoup爬取场景)

解决API请求406错误并爬取学校列表数据

问题背景

目标爬取https://inview.doe.in.gov/state/1088000000/school-list的学校列表,希望仅用BeautifulSoup(不使用Selenium)实现。发现页面内容动态加载,找到两个API接口,但请求时返回406错误,错误提示如下:

{"message":"The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request. Supported entities are: application/json, application/vnd.tembo.api+json, application/vnd.tembo.api+json;version=1","status":406}

问题原因

406错误源于请求的Accept头不符合API要求:API仅接受application/json、application/vnd.tembo.api+json或application/vnd.tembo.api+json;version=1类型的响应,而原代码中设置的Accept:*/*不被服务器认可。

解决步骤

  1. 修正请求头:将Accept头设置为API支持的格式,比如application/json。
  2. 选择合适的API接口:第二个API接口(api2)的过滤参数包含type==school,更适合获取学校列表数据。
  3. 直接解析JSON响应:API返回的是JSON格式数据,无需用BeautifulSoup处理,直接通过requests解析即可。

修正后的代码

import requests

def fetch_school_data():
    # 目标API接口,包含学校类型过滤条件
    api_url = 'https://inview.doe.in.gov/api/entities?filter=type==district,type==network,type==school,type==state&fields=name,type,id,district_id'
    # 设置符合API要求的请求头
    headers = {"Accept": "application/json"}
    
    response = requests.get(api_url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        # 过滤出仅学校类型的数据
        schools = [item for item in data if item['type'] == 'school']
        # 示例:打印前5条学校数据
        for school in schools[:5]:
            print(f"学校名称: {school['name']}, ID: {school['id']}")
    else:
        print(f"请求失败,状态码: {response.status_code}")
        print(response.text)

if __name__ == "__main__":
    fetch_school_data()

补充说明

  • 若需要关联学校所属地区信息,可以结合第一个API接口获取district数据,再通过district_id字段与学校数据关联。
  • API返回的是结构化JSON数据,无需使用BeautifulSoup解析,直接处理JSON即可满足爬取需求。

内容的提问来源于stack exchange,提问作者theycallmepix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:25:32