Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3中的urlib用法_Python_Python 3.x_Urllib3 - Fatal编程技术网

Python3中的urlib用法

Python3中的urlib用法,python,python-3.x,urllib3,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:

我得到以下错误:

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()
arguement:

response = urllib.request.urlopen(chemcalcURL, bytes(urllib.parse.urlencode(params), encoding="utf-8")
bytes()
必须采用一种编码,对于网站而言,这种编码几乎总是utf-8