相关文章推荐
耍酷的枕头  ·  Job Artifacts API | ...·  3 周前    · 
耍酷的枕头  ·  Dou Jie Home ...·  8 月前    · 
耍酷的枕头  ·  SQL Server ...·  9 月前    · 
耍酷的枕头  ·  python - ...·  9 月前    · 
耍酷的枕头  ·  Cant get any updates ...·  9 月前    · 
耍酷的枕头  ·  Solved: "no json ...·  10 月前    · 
耍酷的枕头  ·  Gson 出现 LinkedTreeMap 问题 ·  10 月前    · 
威武的香瓜  ·  [转]Entity Framework ...·  9 小时前    · 

在python中从请求会话中创建websocket连接

10 人关注

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

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

我在这里发现了一个类似的问题,但还没有得到解答 Python - Websockets 无法验证我的会话

这是我到目前为止的代码(简化了一些)。

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
None
None
发布于 2019-11-15
1 个回答
None
None
发布于 2019-12-06
已采纳
0 人赞同

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

 
推荐文章