Python submit post data using mechanize

纵饮孤独 提交于 2019-12-12 20:21:11

问题


The url that i have to submit to the server looks like this:

www.mysite.com/manager.php?checkbox%5B%5D=5&checkbox%5B%5D=4&checkbox%5B%5D=57&self=19&submit=Go%21

The post data I put it like this:

data = {'checkbox%5B%5D': '4', ....and so on... 'self': '19', 'submit': 'Go%21'}

I encode it:

data = urllib.urlencode(orbs)

and this is how i run it:

resp = mechanize.Request('http://mysite.com/manager.php', data)
cj.add_cookie_header(resp)
res = mechanize.urlopen(resp)
print res.read()

And the error says: That i didnt select any item. How can I do it right without using br.select_form(nr=0) because I have nested forms? Thanks.


回答1:


You double-encoded the checkbox field names; you should use checkbox[] instead of checkbox%5B%5D. Also, because that key name is reused, you probably can't use a dictionary to gather up the arguments.




回答2:


Url encoding is the process of changing string (i.e '[]') into percent-encoded string (i.e '%5B%5D') and url decoding is the opposite operation. So:

checkbox%5B%5D=5&checkbox%5B%5D=4&checkbox%5B%5D=57&self=19&submit=Go%21

is after decoding:

checkbox[]=5&checkbox[]=4&checkbox[]=57&self=19&submit=Go!

In your code you're actually encofing an already-encoded url:

data = {'checkbox%5B%5D': '4', ....and so on... 'self': '19', 'submit': 'Go%21'}
data = urllib.urlencode(orbs)

Instead use decoded data and pass it to urlencode:

data = {'checkbox[]': '4', ....and so on... 'self': '19', 'submit': 'Go!'}
data = urllib.urlencode(orbs)


来源:https://stackoverflow.com/questions/15903034/python-submit-post-data-using-mechanize

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