You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用BeautifulSoup从网页JavaScript中自动提取yValues数组首值

解决方案

一、通用提取yValues数组首个元素的方法

1. 正则表达式匹配(轻量首选)

如果网页中yValues是直接赋值为数组的形式(比如var yValues = [12.3, 45.6, ...];),可以用正则精准匹配数组内容,再转换为Python列表提取首个元素:

import re
import ast
import requests

# 获取页面源码
response = requests.get("目标网页URL")
html = response.text

# 匹配yValues数组的正则,兼容不同的变量声明方式(var/let/const,空格、换行)
pattern = re.compile(r'(?:var|let|const)\s+yValues\s*=\s*(\[.*?\]);', re.DOTALL)
match = pattern.search(html)

if match:
    # 提取数组字符串并转换为Python列表
    array_str = match.group(1)
    y_values = ast.literal_eval(array_str)
    first_value = y_values[0]
    print(first_value)
else:
    print("未找到yValues数组")

说明:re.DOTALL让.匹配换行符,处理多行的数组定义;ast.literal_eval比eval更安全,避免执行恶意代码。

2. JS代码解析(处理复杂场景)

如果yValues的赋值涉及JS表达式(比如计算生成数组),正则无法处理时,可以用js2py库直接执行JS代码片段:

import js2py
import requests

response = requests.get("目标网页URL")
html = response.text

# 提取包含yValues的JS代码块(可以先通过正则定位到相关<script>标签内容)
script_pattern = re.compile(r'<script type="text/javascript">(.*?)</script>', re.DOTALL)
scripts = script_pattern.findall(html)

for script in scripts:
    if 'yValues' in script:
        # 执行JS代码,获取yValues变量
        context = js2py.EvalJs()
        context.execute(script)
        if hasattr(context, 'yValues'):
            first_value = context.yValues[0]
            print(first_value)
            break

需要先安装依赖:pip install js2py

二、Alexa技能中Selenium的适用性分析

Selenium不适合用于Alexa技能:

  • Alexa技能通常运行在AWS Lambda环境中,默认没有浏览器环境,需要额外配置headless Chrome,步骤繁琐且占用更多资源;
  • Selenium启动浏览器耗时较长,会增加Alexa技能的响应延迟,影响用户体验;
  • 相比之下,用requests配合正则或js2py的方案更轻量、快速,完全适配Lambda的无浏览器环境。

内容的提问来源于stack exchange,提问作者Alberto Atzori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:40:40