How to use python urllib2 to send json data for login

岁酱吖の 提交于 2019-11-27 01:37:28

问题


I want to use python urllib2 to simulate a login action, I use Fiddler to catch the packets and got that the login action is just an ajax request and the username and password is sent as json data, but I have no idea how to use urllib2 to send json data, help...


回答1:


import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)

This assumes you're using HTTP POST to send a simple json object with username and password.




回答2:


For Python 3.x

Note the following

  • In Python 3.x the urllib and urllib2 modules have been combined. The module is named urllib. So, remember that urllib in Python 2.x and urllib in Python 3.x are DIFFERENT modules.

  • The POST data for urllib.request.Request in Python 3 does NOT accept a string (str) -- you have to pass a bytes object (or an iterable of bytes)

Example

pass json data with POST in Python 3.x

import urllib.request
import json

json_dict = { 'name': 'some name', 'value': 'some value' }

# convert json_dict to JSON
json_data = json.dumps(json_dict)

# convert str to bytes (ensure encoding is OK)
post_data = json_data.encode('utf-8')

# we should also say the JSON content type header
headers = {}
headers['Content-Type'] = 'application/json'

# now do the request for a url
req = urllib.request.Request(url, post_data, headers)

# send the request
res = urllib.request.urlopen(req)

# res is a file-like object
# ...

Finally note that you can ONLY send a POST request if you have SOME data to send.

If you want to do an HTTP POST without sending any data, you should send an empty dict as data.

data_dict = {}
post_data = json.dumps(data_dict).encode()

req = urllib.request.Request(url, post_data)
res = urllib.request.urlopen(req)



回答3:


You can specify data upon request:

import urllib
import urllib2

url = 'http://example.com/login'
values = YOUR_CREDENTIALS_JSON

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()



回答4:


You can use the 'requests' python library to achieve this:

http://docs.python-requests.org/en/latest/index.html

You will find this example:

http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests (More complicated POST requests)

>>> import requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)

It seems python do not set good headers when you are trying to send JSON instead of urlencoded data.



来源:https://stackoverflow.com/questions/4348061/how-to-use-python-urllib2-to-send-json-data-for-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!