python - 如何使用 selenium webdriver 将现有的登录 token 用于 telegram web

标签 python selenium selenium-webdriver webdriver firefox-profile

我正在尝试读取来自 https://web.telegram.org 的电报消息含 Selenium 。

当我打开https://web.telegram.org时在 firefox 中,我已经登录,但是当从 selenium webdriver(firefox) 打开同一页面时,我得到登录页面。

我看到 telegram web 不使用 cookie 进行身份验证,而是将值保存在本地存储中。我可以使用selenium访问本地存储并在那里拥有 key ,例如:“dc2_auth_key”,“dc2_server_salt”,“dc4_auth_key”,...但我不知道如何处理它们才能登录(如果我这样做需要对它们做一些事情,那么为什么?它是同一个浏览器,为什么在不使用 selenium 的情况下打开时它不能以相同的方式工作?)

重现:

打开 Firefox 并登录 https://web.telegram.org然后运行此代码:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://web.telegram.org")
# my code is here but is irrelevant since im at the login page.
driver.close()

最佳答案

当您使用 Firefox 手动打开 https://web.telegram.org 时,将使用默认 Firefox 配置文件。当您登录并浏览网站时,网站会在您的系统中存储身份验证 Cookie。由于 Cookie 存储在默认 Firefox 配置文件本地存储中,即使重新打开浏览器,您也会自动进行身份验证。

但是,每次在启动 Firefox 时创建一个临时的新 mozprofile 时,GeckoDriver 都会为您的测试启动一个新的 Web 浏览 session ,这可以从以下日志:

mozrunner::runner   INFO    Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-profile" "C:\\Users\\ATECHM~1\\AppData\\Local\\Temp\\rust_mozprofile.fDJt0BIqNu0n"

You can find a detailed discussion in Is it Firefox or Geckodriver, which creates “rust_mozprofile” directory

一旦测试执行完成并调用quit(),临时mozprofile将在以下过程中删除:

webdriver::server   DEBUG   -> DELETE /session/f84dbafc-4166-4a08-afd3-79b98bad1470 
geckodriver::marionette TRACE   -> 37:[0,3,"quit",{"flags":["eForceQuit"]}]
Marionette  TRACE   0 -> [0,3,"quit",{"flags":["eForceQuit"]}]
Marionette  DEBUG   New connections will no longer be accepted
Marionette  TRACE   0 <- [1,3,null,{"cause":"shutdown"}]
geckodriver::marionette TRACE   <- [1,3,null,{"cause":"shutdown"}]
webdriver::server   DEBUG   Deleting session
geckodriver::marionette DEBUG   Stopping browser process

所以,当您使用 Selenium 打开同一页面时、GeckoDriverFirefox 存储在默认 Firefox 配置文件的本地存储中的 cookie 无法访问因此您将被重定向到登录页面

<小时/>

要在本地存储中存储和使用 Cookie 来自动进行身份验证,您需要创建并使用自定义 Firefox 配置文件

Here you can find a relevant discussion on webdriver.FirefoxProfile(): Is it possible to use a profile without making a copy of it?

关于python - 如何使用 selenium webdriver 将现有的登录 token 用于 telegram web,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56443546/

相关文章:

python - 使用 `concurrent.futures.Future` 作为 promise

python - 更改 Pandas 数据框特定列的数据类型

Python 3.4 Selenium 处理 chromedriver 异常

python - 使用 selenium 和 python 从下拉菜单中选择一个选项

c# - 使用扩展方法的 Selenium 并行测试

java - 如何在 Java Selenium 中使用通配符条目进行搜索

python - centos 5 中的 Ambari 2.0 安装

java - WebDriver 打开新标签

java - 使用 Selenium 在 Chrome 中获取整页屏幕截图

python - virtualenv 在写入 bin 之前挂起