ric*_*hie 16 python json urllib2
我想使用python urllib2来模拟登录操作,我使用Fiddler来捕获数据包并得到登录操作只是一个ajax请求,用户名和密码作为json数据发送,但我不知道如何使用urllib2发送json数据,帮忙......
Tho*_*s K 20
import urllib2
import json
# Whatever structure you need to send goes here:
jdata = json.dumps({"username":"...", "password":"..."})
urllib2.urlopen("http://www.example.com/", jdata)
Run Code Online (Sandbox Code Playgroud)
这假设您使用HTTP POST发送带有用户名和密码的简单json对象.
tre*_*der 20
请注意以下内容
在Python 3.x中,urllib和urllib2模块结合在一起.该模块已命名urllib.所以,请记住,urllib在Python 2.x和urllibPython 3.x中是不同的模块.
urllib.request.RequestPython 3中的POST数据不接受字符串(str) - 您必须传递一个bytes对象(或一个可迭代的bytes)
json在Python 3.x中使用POST 传递数据
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
# ...
最后请注意,如果您要发送一些数据,则只能发送POST请求.
如果要在不发送任何数据的情况下执行HTTP POST,则应将空dict作为数据发送.
data_dict = {}
post_data = json.dumps(data_dict).encode()
req = urllib.request.Request(url, post_data)
res = urllib.request.urlopen(req)
您可以根据要求指定数据:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31148 次 |
| 最近记录: |