【问题标题】:Python issue: Can't fetch xhr-polling data using Requests libraryPython 问题:无法使用 Requests 库获取 xhr-polling 数据
【发布时间】:2013-05-27 18:30:27
【问题描述】:

首先,让我对 Stack Overflow 社区表示感谢 - 虽然我以前没有发过帖子,但我已经找到了无数解决我过去问题的方法。我非常感谢社区投入的时间和精力,使其成为适合所有人的优秀资源。

我正在尝试从使用 Socket.IO 和 XHR 轮询数据的服务器获取数据。虽然我似乎可以连接 Python 脚本,但我无法正确接收数据。

我查看了 Fiddler 中的传出和传入数据包:每隔约 5 秒,浏览器就会收到有用的信息(即 '5:::{"name":"pollData","args":["<. . python noop>

代码有问题的部分:

reply = requests.get(URL + "/socket.io/1/?t=" + str(long(time.time()*1000)), headers=headers)

session_id = reply.text.split(':')[0]

print "Session ID:", session_id

reply = requests.post(URL + "/socket.io/1/xhr-polling/" + session_id + "?t=" +             
                      str(long(time.time()*1000)), data=message, headers=headers)

print "Successfully subscribed."

for i in range(5):
    sleep(5)
    reply = requests.get(URL + "/socket.io/1/xhr-polling/" + session_id + "?t=" + 
                         str(long(time.time()*1000)), headers=headers)
    print reply.text

我尝试使用 Websocket 客户端,但它产生了这个错误:WebSocketException: Handshake Status 200

SocketIO-client 产生这个错误:SocketIOError: Could not建立连接

比使用另一个库来解决这个问题更重要的是,我想了解为什么会发生这种情况。脚本和 Chrome 生成的传出数据包看起来,至少在外行看来,基本相同 - 为什么它们会产生如此不同的结果?

(欢迎提出任何问题或索取更多信息。)

【问题讨论】:

    标签: python websocket socket.io fiddler python-requests


    【解决方案1】:

    以防万一它在未来对某人有益,经过多次试验和错误,我意识到它需要一个 GET 请求才能发布订阅信息。下面的一些代码可能是多余的,但它似乎工作:

    reply = requests.get(url + "?t=" + get_timecode(), stream=True)
    session_id = reply.text.split(':')[0]
    main = requests.Session()
    
    print "Session ID:", session_id
    
    reply = main.get(url + "xhr-polling/" + session_id + "?t=" + get_timecode(),  
                     stream=True)
    reply = main.post(url + "xhr-polling/" + session_id + "?t=" + get_timecode(),
                      data=subscribe, stream=True)
    
    print "Successfully subscribed."
    
    while 1:
        reply = main.get(url + "xhr-polling/" + session_id + "?t=" + get_timecode(),
                         stream=True)
    

    [请注意,这只是必要的,因为服务器的 websocket 已损坏并且 Socket.IO 不得不回退到 XHR 轮询。此外,可能还有更简单的方法可以做到这一点。]

    【讨论】:

    • 我认为您可以通过 session_id='0' 获取会话 ID,您可以在后续请求中使用该 ID。还是“1”?
    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2012-03-20
    • 2018-08-07
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多