【问题标题】:How to post data to a website, store cookies, then get another page如何将数据发布到网站、存储 cookie,然后获取另一个页面
【发布时间】:2014-09-04 12:23:30
【问题描述】:

我尝试使用 Mechanize 解决问题,但无法正常工作。

只有在登录后发送 cookie 时,网站才允许访问数据。我需要执行以下操作:

  1. 使用 POST 登录页面
  2. 存储 cookie
  3. 访问受保护的页面

【问题讨论】:

  • 请具体说明。网站是什么?你试过什么?
  • 不要只是要求我们为您编写代码,您应该向我们展示您已经尝试过的工作,然后我们可以帮助您解决问题。

标签: python cookies flask mechanize


【解决方案1】:

您可以在Requests 中使用会话。来自documentation

Session 对象允许您在 要求。它还在所有请求中保留 cookie 会话实例。

以下是登录和后续请求的外观可能

import requests

s = requests.Session(verify='my_cert_file.crt')
r = s.post('https://secure-site.com/login', data={
    'username': my_username,
    'password': my_password,
})
# logging in sets a cookie which the session remembers
print s.cookies
r = s.get('https://secure-site.com/secure-data')
print r.json()

【讨论】:

    【解决方案2】:

    我使用 Mechanize 提出了以下解决方案。 Cookie 由mechanize.Browser 管理。

    br = mechanize.Browser()   
    resp = br.open('https://xxxxxxxxxxxxxxxxxxx')
    br.select_form(nr=0)
    br['username'] = username
    br['password'] = password
    response = br.submit()
    time.sleep(1)
    resp_second = br.open('https://secretwebpage')
    print resp_second.read()
    

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多