Python POST data should be bytes, an iterable of bytes, or a file object. It ...

简介: Python POST data should be bytes, an iterable of bytes, or a file object. It ...
# 使用 urllib
import urllib.request
# 使用 json
import json
# 定义 header
headers = {
  # UA 最基本的防爬识别
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
# 请求地址
url = 'https://fanyi.baidu.com/sug'
# 参数
params = {
  'kw': '名称'
}
# post 请求,参数不能进行拼接,需放到请求对象指定的参数对象中
# 通过 urllib.parse.urlencode() 进行转换(多个参数)
# str = urllib.parse.urlencode(params)
# 直接使用转换的参数字符串会报错:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
# request = urllib.request.Request(url=url, data=str, headers=headers)
# 上面直接使用参数字符串会报错,是因为 post 请求参数必须要要进行编码,指定编码格式
data = urllib.parse.urlencode(params).encode('utf-8')
# 模拟浏览器向服务器发送请求
request = urllib.request.Request(url=url, data=data, headers=headers)
# 模拟浏览器向服务器发送请求
response = urllib.request.urlopen(request)
# 获取内容字符串
content = response.read().decode('utf-8')
# 将字符串转成 json
obj = json.loads(content)
# 输出 json
print(obj)
相关文章
|
11月前
|
Python
Python错误 TypeError: ‘NoneType‘ object is not subscriptable解决方案汇总
Python错误 TypeError: ‘NoneType‘ object is not subscriptable解决方案汇总
|
1月前
|
存储 设计模式 Python
Python中的类(Class)和对象(Object)
Python中的类(Class)和对象(Object)
30 0
|
3月前
|
Python
Python学习 -- 根类object
Python学习 -- 根类object
16 0
|
4月前
|
编解码 Python Windows
Python文件路径报错SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3: t
Python文件路径报错SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3: t
|
6月前
|
Python
Python学习 -- 根类object
Python学习 -- 根类object
53 0
|
8月前
|
Python
Python3 ‘str‘ object has no attribute ‘decode‘. Did you mean: ‘encode‘?
Python3 ‘str‘ object has no attribute ‘decode‘. Did you mean: ‘encode‘?
171 0
|
11月前
|
Python
Python 报错AttributeError: ‘str‘ object has no attribute ‘decode‘解决办法
Python 报错AttributeError: ‘str‘ object has no attribute ‘decode‘解决办法
|
11月前
|
Python
Python 数值类型方法|内建函数的对比汇总 (int bool float complex bytes str)
Python 数值类型方法|内建函数的对比汇总 (int bool float complex bytes str)
87 0
|
11月前
|
NoSQL Redis 索引
一日一技:Python的bytes型数据的迭代特征
一日一技:Python的bytes型数据的迭代特征
95 0
|
存储 索引 Python
Python函数是所谓的第一类对象(First-Class Object)是什么鬼?
之前写过一篇关于装饰器的文章,虽然写得还算不错,但是也有不少同学表示没看懂,我大概分析了其中的原因,主要问题是他们不理解函数,因为Python中的函数不同于其它语言。
115 0