python Beautifulsoup:获取script脚本标签和内容

获取所有脚本标签

要获取所有脚本标签,我们需要使用 find_all() 函数

from bs4 import BeautifulSoup # Import BeautifulSoup module


html = '''
<head>

<script src="/static/js/prism.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/main.js"></script>

<script> console.log('Hellow BeautifulSoup') </script>
</head>

'''

soup = BeautifulSoup(html, 'html.parser')

scripts = soup.find_all("script")

for script in scripts:
    print(script)

输出:

<script src="/static/js/prism.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/main.js"></script>
<script> console.log('Hellow BeautifulSoup') </script>

获取脚本文件附带的脚本标签

获取 <script> 标签的 src 属性值,需要:

  • 使用 find_all() 函数
  • 设置 src=True 参数
html = '''
<head>

<script src="/static/js/prism.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/main.js"></script>

<script> console.log('Hellow BeautifulSoup') </script>
</head>

'''

soup = BeautifulSoup(html, 'html.parser') # ?️ Parsing

scripts = soup.find_all("script", src=True) # ?️ Find all script tags that come with the src attribute


for script in scripts:
    print(script['src'])

输出:

/static/js/prism.js
/static/js/bootstrap.bundle.min.js
/static/js/main.js

获取脚本标签的内容

要获取脚本标签的内容,需要使用 .string 属性。但是,让我们看一个例子:

html = '''
<head>

<script src="/static/js/prism.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="/static/js/main.js"></script>

<script> console.log('Hellow BeautifulSoup') </script>
</head>

'''

soup = BeautifulSoup(html, 'html.parser') # ?️ Parsing

scripts = soup.find_all("script", string=True) # ?️ Find all script tags

print(scripts) # ?️ Print Result

for script in scripts: # ?️ Loop Over scripts
    print(script.string)

输出:

[<script> console.log('Hellow BeautifulSoup') </script>]
console.log('Hellow BeautifulSoup')

参考:
https://www.code8cn.com/get-script-beautifulsoup.html


原文出处:/show_1GWU4uTmDcN.html