Arian
Arian

Reputation: 65

convert curl to urllib python3

I tried to convert this CURL command to urllib

curl:

curl -X POST 'http://118.tct.ir/exe/indseane17.pgm' --data 'cmbPro=%CA%E5%D1%C7%E4%0D%0A&pcity=021+++++&lname=%C7%E3%ED%D1%C7%E3%CC%CF%ED&fname=%CD%D3%E4&adrs=&hideme=PZ83M6S2W7'

urllib:

from urllib.request import Request, urlopen
import urllib
data = urllib.parse.urlencode({
     'cmbPro':'%CA%E5%D1%C7%E4%0D%0A',
     'pcity':'021+++++',
     'lname':'%C7%E3%ED%D1%C7%E3%CC%CF%ED',
     'fname':'%CD%D3%E4&adrs=&hideme=PZ83M6S2W7'
     })
data = data.encode('ascii')
q = Request('http://118.tct.ir/exe/indseane17.pgm',data=data)

a = urlopen(q).read()
print(a)

but I've got this error:

HTTPError: HTTP Error 404: Not Found

But when I try it with curl it simply works just fine.

What's the problem?

Upvotes: 2

Views: 1606

Answers (1)

Gennady Kandaurov
Gennady Kandaurov

Reputation: 1964

String cmbPro=%CA%E5%D1%C7%E4%0D%0A&pcity=021+++++&lname=%C7%E3%ED%D1%C7%E3%CC%CF%ED&fname=%CD%D3%E4&adrs=&hideme=PZ83M6S2W7 is already urlencoded and you can use it as it is. There is no 404 with the following:

from urllib.request import Request, urlopen
import urllib

data = 'cmbPro=%CA%E5%D1%C7%E4%0D%0A&pcity=021+++++&lname=%C7%E3%ED%D1%C7%E3%CC%CF%ED&fname=%CD%D3%E4&adrs=&hideme=PZ83M6S2W7'
data = data.encode('ascii')
q = Request('http://118.tct.ir/exe/indseane17.pgm', data=data)

a = urlopen(q).read()
print(a)  # <html>...</html>

Upvotes: 2

Related Questions