【问题标题】:Create websocket connection from requests session in python从python中的请求会话创建websocket连接
【发布时间】:2020-03-11 00:05:03
【问题描述】:

我需要通过 websocket 连接从网站接收数据。只有在登录网站后才能访问 websocket。在 python 请求中使用会话,我可以将我的登录信息发布到登录页面并验证我的详细信息。 Websocket-client 将用于创建到网站的 websocket 连接,但是创建的 websocket 连接不会通过登录会话。

通过请求登录后如何创建websocket连接?

我在这里找到了一个类似的问题,但尚未得到解答 Python - Websockets Unable to validate my session

这是我目前的代码(稍微简化了一点)。

import requests
from bs4 import BeautifulSoup
import base64
import random
import websocket

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}

payload = {
    'username': 'username',
    'password': 'password'}

session = requests.Session()

r = session.get("https://www.example.com/login", headers=headers)

soup = BeautifulSoup(r.content, 'html.parser')
payload['token'] = soup.find('input', attrs={'name': 'token'})['value']

r = session.post("https://www.example.com/login", data=payload, headers=headers)
r = session.get("https://www.example.com/", headers=headers)

headers['Sec-WebSocket-Key'] = str(base64.b64encode(bytes([random.randint(0, 255) for _ in range(16)])), 'ascii')
headers['Sec-WebSocket-Version'] = '13'
headers['Upgrade'] = 'websocket'

ws = websocket.WebSocketApp('wss://www.example.com/streaming/',
                            header=headers,
                            #session=session????)
ws.run_forever()

【问题讨论】:

    标签: python websocket python-requests


    【解决方案1】:

    经过大量搜索,我最终找到了问题的根源。通过 chrome 浏览器访问网站时,我使用 Chrome 开发工具查看网络数据包,但是 Chrome 开发工具不显示 websocket 请求的 cookie。 Firefox 开发者工具确实显示了 websocket 请求的 cookie,而我只在使用 Firefox 时才发现发送了哪些 cookie。 解决方案是为 Requests Session 提取 cookie,并将这些 cookie 传递给 WebSocketApp。这样,websocket 服务器就可以验证您是否已登录。

    cookies = session.cookies.get_dict()
    ws = websocket.WebSocketApp('wss://www.example.com/streaming/',
                            header=headers,
                            cookie="; ".join(["%s=%s" %(i, j) for i, j in cookies.items()]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多