python - 在 python 请求模块中查找 javascript 和 css 中的注释
问题描述
我正在尝试查找 JavaScript 和 CSS 页面中的所有评论。此代码在 HTML 页面中查找 HTML 注释。
import requests
from bs4 import BeautifulSoup as BS
from bs4 import Comment
with requests.session() as r:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get('https://example.com/page.js', verify=False, headers=headers)
response = r.text
soup = BS(response, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for c in comments:
print(c)
但是对于 JavaScript 和 CSS,注释在 /* 和 */ 之间。有什么方法可以修改该代码以检索 JavaScript 或 CSS 注释。
解决方案
我对 BeautifulSoup 不够熟悉,但你可以找到评论在哪里,使用response.find('/*')
,response.find('*/')
在循环中,使用find
的第二个参数,开始寻找下一条评论,只有在前一条结束之后。
免责声明:您仍然可以将 /* 或 */ 作为文本而不是评论,这更难以应对。
推荐阅读
- if-statement - 使用复选框限制结果的 Google 表格跨表格查询
- javascript - 如何将 FullCalendar v3 中的事件拖放限制为仅全天部分?
- system-verilog - SystemVerilog中的有符号和无符号定点乘法
- sql - 在 case 表达式中如何解决这个问题?
- tensorflow - 如何在 TF 2.0 中实现梯度反转层?
- excel - 如何在 WScript.Shell 命令中使用变量?
- ios - 使用即时标记接口共享屏幕截图不会调用 didSelectPost()
- sql-server - 为什么 FireDAC 忽略索引名称?
- mysql - 是否为 INSERT IGNORE ... SELECT 指定了插入顺序?
- python - 何时使用交叉验证和网格搜索在 imblearn 管道中进行特征选择