【问题标题】:How to fetch localStorage attributes from a webpage in python?如何从 python 中的网页获取 localStorage 属性?
【发布时间】:2020-02-27 19:04:24
【问题描述】:

我想获取存储在开发人员工具中“应用程序”选项卡下的 LocalStorage 对象中的特定密钥。

我使用请求来访问网页,但我一直在尝试使用带有 selenium 的 python 绑定来获取元素。但是元素上的 execute_script 获取为 none

from selenium.webdriver import Firefox


browser = Firefox(options=opts)
browser.get('https://stackoverflow.com')
print (browser.execute_script('return localStorage.getItem("se:fkey");'))

【问题讨论】:

    标签: python selenium-webdriver python-requests


    【解决方案1】:

    我确实相信您的代码原则上有效,因为我得到以下结果:

    Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from selenium.webdriver import Firefox
    >>> browser = Firefox()
    >>> browser.get('https://stackoverflow.com')
    >>> print(browser.execute_script('return localStorage.setItem("bla", "blub");'))
    None
    >>> print(browser.execute_script('return localStorage.getItem("bla");'))
    blub
    

    对于您使用的示例,我得到:

    >>> from selenium.webdriver import Firefox
    >>> browser = Firefox()
    >>> browser.get('https://stackoverflow.com')
    >>> print(browser.execute_script('return localStorage.getItem("se:fkey");'))
    a65d3ff60687075dfa4fa896a4a1013469e1cabe47542b72924674be03c0c2ee,1583582386
    

    但是,请注意,正在启动的浏览器使用的是干净的浏览器配置文件,其中(除了 cookie、书签、历史记录等)本地存储是干净的。因此,即使您在“普通”firefox 配置文件中设置了一些本地存储值,由 selenium 启动的 Firefox 浏览器也无法访问“您的”本地存储。

    可能在初始化浏览器时将特定的浏览器配置文件传递给options 参数(请参阅https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.firefox.options)。但是,请注意,这会使您的代码很难在另一台机器上重用...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2011-09-20
      • 1970-01-01
      相关资源
      最近更新 更多