Using Python Requests to Select Forms

本秂侑毒 提交于 2019-12-07 14:48:28

问题


I would like to use a python library capable of filling out forms and handling redirects:

  1. The "home" page has a form {'username':'user', 'password':'pass'}
  2. The "redirect" page brings me to a new page
  3. The "new" page has a link to the final page
  4. The "final" page has a form {'Field 1':'Data 1', 'Field 2':'Data 2'}

I would like to get to the "final" page and fill out the form. I have already looked through every post in SO for python-requests, read the API doc and the entire user-guide.

I have been able to use mechanize to fill out "home" page forms:

import mechanize
# Fill out Log In form
br = mechanize.Browser()
br.open('http://www.yourfavoritesite.com')
br.select_form(nr=0)
br['username'] = 'user'
br['password'] = 'pass'
br.submit()

Additionally -- after disabling the redirect on the webpage -- I have been able to use mechanize to fill out "new" page forms:

# Click link
br.find_link(text='Admin')
req = br.click_link(text='Admin')
br.open(req)

# Fill out Final form
br.select_form(nr=0)
br['Field 1'] = 'Data 1'
br['Field 2'] = 'Data 2'
br.submit()

What happens if I don't disable the redirect and the page redirects is I don't make it to the "new" page and when I try to fill out the form I get the following error:

File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/mechanize/_mechanize.py", line 524, in select_form
     raise FormNotFoundError("no form matching "+description)
mechanize._mechanize.FormNotFoundError: no form matching nr 0

I have heard that Python Requests is very simple and I would like to use this library assuming I could do something along the line of:

import requests
# Fill out Log In form
data = {'username':'admin', 'password':'pass'}
r = requests.get('http://www.yourfavoritesite.com', allow_redirects=True)
r = requests.put(r.url, data=data)

# Follow redirect to "new" page

# Click link
# I haven't heard of this feature in requests

# Fill out Final form
data = {'Field 1':'Data 1', 'Field 2':'Data 2'}
r = requests.put(r.url, data=data)

回答1:


I know this is old but I believe that the answer you're looking for from requests is (obviously) not get, but post.

from: http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests

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


来源:https://stackoverflow.com/questions/10507169/using-python-requests-to-select-forms

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