【问题标题】:Python: Access sessionStorage using requestsPython:使用请求访问 sessionStorage
【发布时间】:2021-07-21 06:56:49
【问题描述】:

我需要使用python requests 模块访问sessionStorage(与javascript一样)对象,有没有办法实现我的目标;我看过其他答案,但似乎没有一个对我想要完成的任务有足够的回应

如果没有办法,除了使用 selenium 之外,我还有什么其他选择(因为有办法这样做)?

简单来说

我想这样做:

var x = sessionStorage; // js code

但是在 python 3.9 中:)

【问题讨论】:

  • sessionStorage 由浏览器运行时提供,如果你的代码在浏览器之外运行,则该对象不存在。
  • @georg 那么有没有办法在运行时执行js代码而不需要硒

标签: javascript python python-3.x session python-requests


【解决方案1】:

IIUC:以下代码用于将网页中的 sessionStorage 属性值提取到 Python dict

import re
import json
from bs4 import BeautifulSoup as bs
import requests

# Setup.
site = 'http://www.some-site.com/page'
exp = '^[\n\s]+sessionStorage.setItem\(.*JSON.stringify\((?P<content>{.*})\)\)'

r = requests.get(site)
if r.status_code == 200:
    soup = bs(r.text)
    # Extract all <script> tags from the full HTML.
    scripts = soup.findAll('script')
    # Loop through all <script> tags until sessionStorage is found.
    script = [s.string for s in scripts if 'sessionStorage' in s.decode()]
    # Use regex (with a named capture group) to extract the JSON data.
    m = re.match(exp, script[0])
    if m:
        content = m['content']
        # Convert scraped JSON data to a dict.
        data = json.loads(content)

注意:正则表达式模式可能需要修改以适合您(用户)的特定用例。

TL;DR(背景):

我在自己搜索上述代码的更优雅的解决方案时遇到了这个问题。

在我的例子中,我正在为一个站点编写单元测试,并且需要从特定网页中获取 sessionStorage 属性来测试它是否包含预期的元素。由于数据是 JSON 格式,此代码提取 JSON 数据并转换为 Python dict 以供检查。

【讨论】:

    【解决方案2】:

    如果您使用 ajax 从服务器获取信息,则应先包含您的 sessionStorage 数据,然后将其附加到请求中,如

    myStorage = window.sessionStorage;
    let token = myStorage.getItem('token')
    
    $.get(url, { token: token }, function(response)() }
    

    或者,如果您不使用 Ajax,并且每次通过刷新页面来切换页面,您可以使用 cookie 与会话存储,然后服务器可以提取

    # Python
    import os, sys
    
    sys.stderr.write("cookies:", os.getenv('HTTP_COOKIE'))
    

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2017-10-07
      • 2023-03-24
      • 2018-11-19
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多