2024-04-20 10:24:26 发布
网友
我有这样的块的html文件:
<script type="text/javascript> var json1 = { // ... } </script>
使用变量的名称-例如“json1”-提取json的简单方法是什么?正则表达式可以吗,或者我需要像靓汤这样的东西?你知道吗
我发现一些简单的东西在我的案子里有用。获取“var json1=”的位置,然后调用html.find文件(“”,startOfJson1)。使用索引从字符串中分割json。你知道吗
是的,你需要正则表达式和靓汤
import json import re from bs4 import BeautifulSoup # $ pip install beautifulsoup4 html = //Your html output soup = BeautifulSoup(html) script = soup.find('script', text=re.compile('json1')) json_text = re.search(r'^\s*json1\s*=\s*({.*?})\s*;\s*$', script.string, flags=re.DOTALL | re.MULTILINE).group(1) data = json.loads(json_text) print(data['json1'])
我发现一些简单的东西在我的案子里有用。获取“var json1=”的位置,然后调用html.find文件(“”,startOfJson1)。使用索引从字符串中分割json。你知道吗
是的,你需要正则表达式和靓汤
相关问题 更多 >
编程相关推荐