【问题标题】:Get item from browser local storage with python使用python从浏览器本地存储中获取项目
【发布时间】:2021-09-07 09:17:22
【问题描述】:

我正在尝试使用 Python 读取我通过 Javascript 放入浏览器的键的值。
有没有比selenium 更简单的方法呢?
使用selenium 只是为了获得localStorage 项目似乎很麻烦。

Javascript 将用户名放入localStorage

userName = window.prompt("Please enter your name", "Name...");
localStorage.setItem("name", userName.toString());

是否有 Python 中的 localStorage.getItem("name") 等价于 Javascript ?

【问题讨论】:

  • 为什么会有? Python 和网络浏览器之间几乎没有什么关系。
  • 尝试:driver.execute_script("window.localStorage.getItem('key');")
  • 谢谢,猜猜selenium 没办法了

标签: javascript python


【解决方案1】:

对于像我一样对整个事情不熟悉的人,我现在解决了这个问题,方法是按照其他人在其他类似问题的答案中所说的话,并使用 Post 将键值从 localstorage 发送到 python。由于用户无论如何都必须上传文件,因此我使用javascript动态创建了上传表单并使用隐藏类型的输入元素来发送变量中的密钥(因为我们正在谈论用户名,这显然因用户而异)到蟒蛇

function createUploadForm(){
    let userName = localStorage.getItem("username");
    let form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("action", "/upload");

    //create hidden input element for user ID
    let userID = document.createElement("input");
    userID.setAttribute("type", "hidden");
    userID.setAttribute("id", "userID");
    userID.setAttribute("name", "userID");
    userID.setAttribute("value", userName);

在 python 网站上,我通过烧瓶 (@app.route) 收到了这个

user = flask.request.form.get("userID")

【讨论】:

    【解决方案2】:

    据我所知,只有 Javascript 可以与浏览器(客户端)交互,并且它是唯一的原生 Web 客户端编程语言。本地存储是一种浏览器功能,因此您只能使用 Javascript 访问此功能。 Python 在这种情况下无能为力。

    【讨论】:

    • 浏览器也支持WebAssembly。您可以使用许多不同的语言编写代码,例如 C、C++、Go、Rust 或 AssemblyScript,并转译/编译为 WebAssembly
    猜你喜欢
    • 2019-06-21
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多