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

如何将BeautifulSoup获取的动态JS字符串格式列表列表转为Python列表?

Absolutely! Converting that stringified list-of-lists into a usable Python structure is totally doable—no need to rely on Selenium for this specific step. Here are a few reliable, straightforward methods you can use:

This is the go-to method for parsing string representations of Python literal structures (like lists, dictionaries, tuples, etc.). Unlike the risky eval() function, ast.literal_eval() only evaluates safe, valid Python literals, so it won’t execute malicious code hidden in your string.

Here’s how to use it:

import ast

# Example stringified list-of-lists (yours will be longer, but the logic is the same)
raw_str_data = "[[123, 'product_name', 49.99], [456, 'another_item', 29.99], [789, 'third_product', 99.99]]"

# Convert to a real Python list
usable_list = ast.literal_eval(raw_str_data)

# Verify it works
print(type(usable_list))  # Output: <class 'list'>
print(usable_list[0])     # Output: [123, 'product_name', 49.99]

It handles all Python-specific types like True, False, None, single-quoted strings, and nested structures flawlessly—perfect for your 16k+ character string.

2. Use json.loads() (If Your Data Is JSON-Compatible)

If your string follows JSON syntax rules (double-quoted strings, lowercase true/false/null instead of Python’s True/False/None), the json module will work great. If not, you can tweak the string to match JSON format first.

Example with native JSON format:

import json

# JSON-compliant string (double quotes, lowercase booleans/null)
json_str_data = '[["123", "product_name", 49.99], ["456", "another_item", 29.99]]'

usable_list = json.loads(json_str_data)
print(usable_list)  # Output: [['123', 'product_name', 49.99], ['456', 'another_item', 29.99]]

Example with Python-style string (needs conversion):

If your original string uses Python conventions, do quick replacements to make it JSON-friendly:

import json

raw_str_data = "[[123, 'product_name', True], [456, 'another_item', None]]"
# Convert Python syntax to JSON syntax
json_compatible_str = (
    raw_str_data.replace("'", '"')
                .replace("True", "true")
                .replace("False", "false")
                .replace("None", "null")
)

usable_list = json.loads(json_compatible_str)
print(usable_list)  # Output: [[123, 'product_name', True], [456, 'another_item', None]]

Note: This replacement can hit edge cases (like strings containing single quotes), so ast.literal_eval() is still more robust for Python-specific data.

3. Manual Parsing (Last Resort)

If for some reason the above methods fail (e.g., your data has weird custom formatting), you could parse the string manually using regex or string splitting. This is error-prone and tedious, but here’s a simplified example:

import re

raw_str_data = "[[123, 'product_name', 49.99], [456, 'another_item', 29.99]]"

# Strip outer brackets
inner_content = raw_str_data.strip("[]")
# Split into individual sub-list strings
sub_list_strings = re.split(r'],\s*\[', inner_content)

usable_list = []
for sub_str in sub_list_strings:
    # Clean up sub-list and split into elements
    elements = re.split(r',\s*', sub_str.strip("[]"))
    processed_elements = []
    for elem in elements:
        # Convert elements to appropriate types (simplified example)
        if elem == "True":
            processed_elements.append(True)
        elif elem == "False":
            processed_elements.append(False)
        elif elem.startswith("'") and elem.endswith("'"):
            processed_elements.append(elem.strip("'"))
        elif elem.replace(".", "").isdigit():
            processed_elements.append(float(elem) if "." in elem else int(elem))
        else:
            processed_elements.append(elem)
    usable_list.append(processed_elements)

print(usable_list)  # Output: [[123, 'product_name', 49.99], [456, 'another_item', 29.99]]

Only use this if you have no other option—you’ll need to handle every possible data type and edge case manually.


内容的提问来源于stack exchange,提问作者Mr. Confused

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:43:34