python - Python 3 中的 urllib 使用

标签 python python-3.x urllib3

我收到以下错误:

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

调用下面的电话时

import urllib.request, urllib.parse, urllib.error, urllib.request, 
urllib.error, urllib.parse
import json

chemcalcURL = 'http://www.chemcalc.org/chemcalc/em'

# Define a molecular formula string
mfRange = 'C0-100H0-100N0-10O0-10'
# target mass
mass = 300

# Define the parameters and send them to Chemcalc
# other options (mass tolerance, unsaturation, etc.
params = {'mfRange': mfRange,'monoisotopicMass': mass}


response = urllib.request.urlopen(chemcalcURL, urllib.parse.urlencode(params))

# Read the output and convert it from JSON into a Python dictionary
jsondata = response.read()
data = json.loads(jsondata)

print(data)

最佳答案

您必须将请求转换为字节,这涉及使用 bytes() 争论:

response = urllib.request.urlopen(chemcalcURL, bytes(urllib.parse.urlencode(params), encoding="utf-8")

bytes() 必须采用网站编码,该编码几乎始终为 utf-8。

关于python - Python 3 中的 urllib 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968918/

相关文章:

python - 从系列中删除分钟和小时

python - 使用列表项的 "existence"作为 Python 的 if 条件语句

python - 将 Python 3 打开(编码 ="utf-8")向后移植到 Python 2

python - 使用 python Requests 库从 Twitter 的用户流中消费 - 如何检测断开连接?

python - 从关系属性访问列值

python对象类型转换

python - 单击事件清除 QLineEdit

django - 即使在我的 Django 管理页面中,静态文件也没有被加载

python - 轻松升级 Requests 的 urllib3 版本?

python - 在 io.TextIOWrapper 中包装 urllib3.HTTPResponse