【问题标题】:Session timeout in PythonPython中的会话超时
【发布时间】:2016-06-06 06:28:47
【问题描述】:

这是我正在使用的代码。

import requests

headers = { 'Accept':'*/*',
            'Accept-Language':'en-US,en;q=0.8',
            'Cookie':'Cookie:PHPSESSID=vev1ekv3grqhh37e8leu1coob1',
            'Cache-Control':'max-age=0',
            'Connection':'keep-alive',
            'Proxy-Authorization':'Basic ZWRjZ3Vlc3Q6ZWRjZ3Vlc3Q=',
            'If-Modified-Since':'Fri, 13 Nov 2015 17:47:23 GMT',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
            }


with requests.Session() as c:
    url = 'http://172.31.13.135/tpo/spp/'
    c.get(url, headers=headers)
    payload = {'regno': 'myregno', 'password': 'mypassword'}
    c.post(url, data = payload, headers=headers)
    r = c.get('http://172.31.13.135/tpo/spp/home.php', headers=headers)
    print r.content

我在运行此脚本时收到以下消息。

<script>
alert("Session timeout !");
window.location = "logout.php";
</script><script>
alert("Unauthorised Access!");
window.location = "index.php";
</script>

<!DOCTYPE html>
<html lang="en">

我该如何处理这个“会话超时”问题?

非常感谢。

【问题讨论】:

    标签: python session post timeout python-requests


    【解决方案1】:

    当我无法访问网站进行抓取时,真的很难回答。 所以这是我的猜测,

    1) 尝试从您不需要的标头中删除 cookie。 因为requests.Session()会在你第一次访问url = 'http://172.31.13.135/tpo/spp/'时生成自己的cookies。

    So your headers will be,
    
    headers = { 'Accept':'*/*',
                'Accept-Language':'en-US,en;q=0.8',
                'Cache-Control':'max-age=0',
                'Connection':'keep-alive',
                'Proxy-Authorization':'Basic ZWRjZ3Vlc3Q6ZWRjZ3Vlc3Q=',
                'If-Modified-Since':'Fri, 13 Nov 2015 17:47:23 GMT',
                'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
                }
    

    2) 确保标题中的 'If-Modified-Since' 字段对于您提到的内容是静态的并且不会改变。如果确实发生了变化,请对其进行相应编码以实时设置日期和时间。

    3) 我不确定你为什么在标题中有'Proxy-Authorization':'Basic ZWRjZ3Vlc3Q6ZWRjZ3Vlc3Q='。尝试没有它的标题。 但是,如果您必须拥有它,请确保此验证代码也是静态的,并且不会每次都更改。

    如果有帮助请告诉我

    【讨论】:

      【解决方案2】:

      您也可以在 get 和 post 方法中传递超时变量:

      timeout = 10  # ten sec.
      with requests.Session() as c:
          url = 'http://172.31.13.135/tpo/spp/'
          c.get(url, headers=headers, timeout=timeout)
          payload = {'regno': 'myregno', 'password': 'mypassword'}
          c.post(url, data = payload, headers=headers, timeout=timeout)
          r = c.get('http://172.31.13.135/tpo/spp/home.php', headers=headers, timeout=timeout)
          print r.content
      

      您可以通过这样做来调整等待响应的最长时间 有关请求的更多信息,请参阅the docs

      【讨论】:

        猜你喜欢
        • 2010-12-05
        • 2012-10-14
        • 2010-10-13
        • 2013-03-01
        • 2017-10-07
        • 2013-03-29
        • 1970-01-01
        相关资源
        最近更新 更多