【问题标题】:How to extract specific script element from HTML using Beautiful Soup如何使用 Beautiful Soup 从 HTML 中提取特定的脚本元素
【发布时间】:2021-01-02 11:52:03
【问题描述】:

我正在使用 BS4 从足球统计页面中提取信息。我是这样开始的:

from bs4 import BeautifulSoup as bs
import requests

res = requests.get(url)
soup = bs(res.content, 'lxml')
scripts = soup.find_all('script')
scripts = [script for script in scripts]

这成功地将所有脚本元素作为列表返回。

我需要提取特定的脚本元素

具体来说,开头如下:

 <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...
</script>

我尝试了以下代码的各种迭代,但输出总是打印为空白:

for script in scripts: 
    if 'teamsData' in script.text: 
        print(script)

我总是可以简单地使用“print(scripts[2])”,但我想知道为什么我最初的努力失败了。

谢谢!

【问题讨论】:

  • 可能跟脚本没有转成字符串有关?

标签: python html json python-3.x beautifulsoup


【解决方案1】:

显然,.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)))

【讨论】:

【解决方案2】:

您可以使用.string 访问&lt;script&gt; 字符串:

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/json 模块。例如:

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'}

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多