使用Python请求选择表单

时间:2012-05-08 21:58:13

标签: python mechanize python-requests

我想使用能够填写表单和处理重定向的python库:

  1. “主页”页面的格式为{'username':'user', 'password':'pass'}
  2. “重定向”页面将我带到新页面
  3. “新”页面包含指向最终页面的链接
  4. “最终”页面的格式为{'Field 1':'Data 1', 'Field 2':'Data 2'}
  5. 我想进入“最终”页面并填写表格。我已经查看了中SO的每个帖子,阅读了API文档和整个用户指南。

    我已经能够使用mechanize来填写“主页”表单:

    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()
    

    此外 - 在禁用网页上的重定向后 - 我已经能够使用mechanize填写“新”页面表单:

    # 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()
    

    如果我不禁用重定向和页面重定向会发生什么,我不会进入“新”页面,当我尝试填写表单时出现以下错误:

    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
    

    我听说Python请求非常简单,我想使用这个库,假设我可以按照以下方式做一些事情:

    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 个答案:

答案 0 :(得分:1)

我知道这已经过时了,但我相信您在requests寻找的答案(显然)不是get,而是post

自: 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"
  },
  ...
}