简体   繁体   中英

urlib usage from Python 3

I get the following error:

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

When making the call below

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)

You have to convert your request to bytes which involves the use of bytes() arguement:

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

bytes() must take an encoding which for websites is almost always utf-8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM