python Beautifulsoup:获取script脚本标签和内容 作者:马育民 • 2025-01-27 21:51 • 阅读:10004 # 获取所有脚本标签 要获取所有脚本标签,我们需要使用 `find_all()` 函数 ``` from bs4 import BeautifulSoup # Import BeautifulSoup module html = ''' ''' soup = BeautifulSoup(html, 'html.parser') scripts = soup.find_all("script") for script in scripts: print(script) ``` 输出: ``` ``` # 获取脚本文件附带的脚本标签 获取 ` ''' 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 = ''' ''' 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) ``` 输出: ``` [] console.log('Hellow BeautifulSoup') ``` 参考: https://www.code8cn.com/get-script-beautifulsoup.html 原文出处:http://malaoshi.top/show_1GWU4uTmDcN.html