# 使用 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)