如何用JavaScript/Node.js从HTML文档字符串中提取指定密钥
Alright, let’s tackle this problem step by step — I’ve been stuck in similar situations where nested HTML and messy script blocks make extracting specific data feel like searching for a needle in a haystack, so I get your frustration. Here’s how I’d approach it:
<script> Tag with an HTML Parser Forget trying to regex your way through the entire HTML document to find the right script tag — nested elements will just lead to false matches. Instead, use a proper HTML parser to zero in on the script block that contains app.init(.
For example, using Python’s BeautifulSoup (it’s lightweight and gets the job done):
from bs4 import BeautifulSoup import re # Replace html_content with your actual page response soup = BeautifulSoup(html_content, "html.parser") target_script = None # Loop through all script tags to find the one with app.init for script in soup.find_all("script"): if script.string and "app.init(" in script.string: target_script = script.string break
This ensures you’re only working with the script that actually contains your target configuration, not every random script on the page.
Once you’ve got the right script, the next step is yanking out the app.init({...}) object. Directly converting the entire script to JSON won’t work because of comments or non-JavaScript-standard syntax, so we’ll clean it up first:
if target_script: # Match everything inside app.init(...) init_match = re.search(r"app\.init\((\{.*?\})\)", target_script, re.DOTALL) if init_match: config_raw = init_match.group(1) # Strip out single-line comments (// ...) config_raw = re.sub(r"//.*?$", "", config_raw, flags=re.MULTILINE) # Strip out multi-line comments (/* ... */) config_raw = re.sub(r"/\*.*?\*/", "", config_raw, flags=re.DOTALL) # Fix unquoted keys (common in JS objects, which JSON hates) config_raw = re.sub(r"(\w+):", r'"\1":', config_raw) # Now try parsing to JSON import json try: config = json.loads(config_raw) # Replace 'a' with your actual key name from the config target_key = config.get("a") print(f"Got your key: {target_key}") except json.JSONDecodeError: # If JSON fails, use Python's AST module (more forgiving for JS-like objects) import ast try: config = ast.literal_eval(config_raw) target_key = config.get("a") print(f"Got your key via AST: {target_key}") except Exception as e: print(f"Still stuck? Error parsing: {str(e)}")
The AST method is a lifesaver here because it can handle JavaScript-style objects that aren’t strictly valid JSON (like unquoted keys or trailing commas).
If the script is obfuscated or the config is generated dynamically, parsing the text might not cut it. In that case, use a JavaScript engine to run the script and directly access the app.init parameters.
Using Python’s execjs (requires Node.js installed):
import execjs # Create a mock app object to capture the init config js_context = execjs.compile(""" var app = { init: function(config) { this.storedConfig = config; } }; """ + target_script) # Extract the config directly from the mock app config = js_context.eval("app.storedConfig") target_key = config.get("a") print(f"Extracted key via JS execution: {target_key}")
This method bypasses all the parsing headaches by letting the JavaScript engine do the work it’s designed for.
内容的提问来源于stack exchange,提问作者Rocky

