2 回答
TA贡献2041条经验 获得超4个赞
显然,.text脚本标签始终为空字符串。但是,您可以从以下位置获取标签的内容.children
from bs4 import BeautifulSoup
from io import StringIO
html = """
<script>
let a = "Hello";
</script>
"""
b = StringIO(html)
soup = BeautifulSoup(b, 'lxml')
for e in soup.find_all('script'):
print(repr(e.text))
print(repr(''.join(e.children)))
TA贡献1943条经验 获得超7个赞
您可以使用以下方式.string访问<script>字符串:
import re
import json
from bs4 import BeautifulSoup
html_doc = '''<script>
var teamsData = JSON.parse('\x7B\x2271\x22\x3A\x7B\x22id\x22\x3A\x2271\x22,\x22title\x22\x3A\x22Aston\x20Villa\x22,\x22history\x22\x3A\x5B\x5D\x7D,\x2272\x22\x3A\x7B\x22id\x22\x3A\x2272\x22\x7D\x7D');
</script>'''
soup = BeautifulSoup(html_doc, 'html.parser')
script_string = soup.find('script').string
print(script_string)
印刷:
var teamsData = JSON.parse('{"71":{"id":"71","title":"Aston Villa","history":[]},"72":{"id":"72"}}');
要解析JSON数据,可以使用re/ jsonmodules。例如:
data = re.search(r"JSON\.parse\('(.*?)'\);", script_string).group(1)
data = json.loads(data)
for k, v in data.items():
print(k, v)
印刷:
71 {'id': '71', 'title': 'Aston Villa', 'history': []}
72 {'id': '72'}
添加回答
举报