html字符串解析json
时间: 2023-11-13 12:03:58 浏览: 49
要解析 HTML 字符串中的 JSON 数据,你可以先找到包含 JSON 数据的部分,然后使用合适的方法将其解析为 JSON 对象。下面是一个示例代码,使用 Python 的 BeautifulSoup 库和 json 库来实现:
```python
from bs4 import BeautifulSoup
import json
html_string = '<html><body><script>var data = {"name": "John", "age": 30};</script></body></html>'
soup = BeautifulSoup(html_string, 'html.parser')
script_tag = soup.find('script')
json_string = script_tag.string
# 提取 JSON 数据
start_index = json_string.find('{')
end_index = json_string.rfind('}') + 1
json_data = json_string[start_index:end_index]
# 解析 JSON 数据
parsed_data = json.loads(json_data)
print(parsed_data)
```
在这个示例中,我们首先使用 BeautifulSoup 解析 HTML 字符串。然后,通过查找 `<script>` 标签,找到包含 JSON 数据的部分。接下来,我们提取出 JSON 数据字符串,并使用 json.loads() 方法将其解析为 JSON 对象。最后,我们打印解析后的 JSON 数据。
请注意,这个示例仅适用于包含在 `<script>` 标签中的简单 JSON 数据。如果你的 HTML 字符串中有其他复杂结构或嵌套的 JSON 数据,你可能需要根据具体情况进行相应的调整。