首页 > 解决方案 > 在 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 注释。

标签: pythonpython-requests

解决方案


我对 BeautifulSoup 不够熟悉,但你可以找到评论在哪里,使用response.find('/*'),response.find('*/')在循环中,使用find的第二个参数,开始寻找下一条评论,只有在前一条结束之后。

免责声明:您仍然可以将 /* 或 */ 作为文本而不是评论,这更难以应对。


推荐阅读