1

我正在尝试使用 selenium从https://web.telegram.org读取电报消息。

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

我看到电报网络没有使用 cookie 进行身份验证,而是将值保存在本地存储中。我可以使用 selenium 访问本地存储,并在那里拥有诸如:“dc2_auth_key”、“dc2_server_salt”、“dc4_auth_key”等密钥,但我不确定如何处理它们才能登录(如果我这样做了需要对他们做点什么,为什么?它是同一个浏览器,为什么在没有硒的情况下打开时它的工作方式不一样?)

重现:

打开 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()
4

2 回答 2

4

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

但是,当GeckoDriver为您的测试启动一个新的 Web 浏览会话时,每次启动Firefox时都会创建一个临时的新mozprofile,这从以下日志中可以明显看出:

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

您可以在 Is it Firefox or Geckodriver 中找到详细讨论,它创建了“rust_mozprofile”目录

一旦测试执行完成并被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

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


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

在这里您可以找到有关 webdriver.FirefoxProfile() 的相关讨论:是否可以使用配置文件而不复制它?

于 2019-06-04T13:37:20.367 回答
0

您可以使用本地存储中的当前数据进行身份验证。例子:

    driver.get(TELEGRAM_WEB_URL);
    LocalStorage localStorage =  ((ChromeDriver) DRIVER).getLocalStorage();
    localStorage.clear();
    localStorage.setItem("dc2_auth_key","<YOUR AUTH KEY>");
    localStorage.setItem("user_auth","<YOUR USER INFO>");
    driver.get(TELEGRAM_WEB_URL);
于 2021-04-04T12:43:23.027 回答