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

Python发送POST请求报错:需bytes类对象而非str,如何修复路由器端口转发脚本

错误原因

  • 你定义的reqInfo不是合法字典,而是集合(set)类型:requests的data参数接收表单数据时要求传入键值对结构的字典,你当前把key: value整体作为单个字符串写入大括号,同时存在多值逗号拆分的错误(比如'786438001000: ', GlobalLanPort会被识别为两个独立的集合元素),不符合参数格式要求。
  • 类型不匹配:你的全局变量(如GlobalLanPort/GlobalWanPort等)大概率是bytes类型,和字符串拼接或者传入表单时没有转成字符串类型,触发a bytes-like object is required, not 'str'报错。

修复方案

将reqInfo改为合法字典结构,统一把所有值转成字符串类型,示例代码如下:

import requests

url = "http://192.168.0.1/apply_abstract.cgi"
reqInfo = {
    'action': 'ui_firewall',
    'httoken': 'REMOVED FOR SAFETY', # 替换为你实际的httoken值
    'submit_button': 'wan_portforwarding.htm',
    '786434001000': str(GlobalForwardingName),
    '786433001000': '1',
    '786435001000': str(GlobalInternalIP),
    '#786437001000': str(GlobalProtocol),
    '786438001000': str(GlobalLanPort),
    '786439001000': str(GlobalLanPort),
    '786440001000': str(GlobalWanPort),
    '786441001000': str(GlobalWanPort)
}

# 可选:如果路由器要求特定请求头可以加上,模拟浏览器请求避免被拦截
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}

sendReq = requests.post(url, data=reqInfo, headers=headers)
# 可打印返回结果确认请求执行状态
print(sendReq.status_code)
print(sendReq.text)

额外验证建议

如果修改后仍然报错,可以打印所有全局变量的类型确认是否存在bytes类型未转换的情况:

print(type(GlobalForwardingName), type(GlobalInternalIP), type(GlobalProtocol), type(GlobalLanPort), type(GlobalWanPort))

如果输出中存在<class 'bytes'>的变量,调用.decode('utf-8')转为字符串即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:09:04