如何在Python中从网页中提取Javascript和CSS文件?

2021年11月16日18:44:27 发表评论 1,104 次浏览

Python从网页提取Javascript和CSS文件?本文构建一个使用请求和 BeautifulSoup 从 Python 网页中提取所有 Javascript 和 CSS 文件的工具。

Python如何提取Javascript和CSS?假设你的任务是分析某个网站以检查其性能,并且你需要提取下载网页才能正确加载所需的全部文件,在本教程中,我将通过构建一个 Python 工具来提取所有文件来帮助你完成该任务链接到特定网站的脚本和 CSS 文件链接。

Python提取Javascript和CSS示例解析:我们将使用requestsBeautifulSoup作为 HTML 解析器,如果你的 Python 上没有安装它们,请执行以下操作:

pip3 install requests bs4

让我们首先初始化 HTTP 会话并将用户代理设置为常规浏览器而不是 Python 机器人:

import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin

# URL of the web page you want to extract
url = "http://books.toscrape.com"

# initialize a session
session = requests.Session()
# set the User-agent as a regular browser
session.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"

现在要下载该网页的所有 HTML 内容,我们需要做的就是调用session.get()方法,该方法返回一个响应对象,我们只对 HTML 代码感兴趣,而不是整个响应:

# get the HTML content
html = session.get(url).content

# parse HTML using beautiful soup
soup = bs(html, "html.parser")

现在我们有了Soup,让我们提取所有脚本和 CSS 文件,我们使用soup.find_all()方法返回所有使用标签和传递的属性过滤的 HTML Soup对象:

# get the JavaScript files
script_files = []

for script in soup.find_all("script"):
    if script.attrs.get("src"):
        # if the tag has the attribute 'src'
        script_url = urljoin(url, script.attrs.get("src"))
        script_files.append(script_url)

因此,基本上我们正在搜索具有src属性的脚本标签,这通常链接到本网站所需的 Javascript 文件。

Python如何提取Javascript和CSS?同样,我们可以使用它来提取 CSS 文件:

# get the CSS files
css_files = []

for css in soup.find_all("link"):
    if css.attrs.get("href"):
        # if the link tag has the 'href' attribute
        css_url = urljoin(url, css.attrs.get("href"))
        css_files.append(css_url)

你可能知道,CSS 文件位于链接标签的href属性内。我们使用urljoin()函数来确保链接是绝对链接(即具有完整路径,而不是相对路径,例如/js/script.js)。

最后,让我们打印全部脚本和 CSS 文件并将链接写入单独的文件,如下是Python提取Javascript和CSS示例

print("Total script files in the page:", len(script_files))
print("Total CSS files in the page:", len(css_files))

# write file links into files
with open("javascript_files.txt", "w") as f:
    for js_file in script_files:
        print(js_file, file=f)

with open("css_files.txt", "w") as f:
    for css_file in css_files:
        print(css_file, file=f)

Python从网页提取Javascript和CSS文件?执行后,将出现 2 个文件,一个用于 Javascript 链接,另一个用于 CSS 文件:

css_files.txt

http://books.toscrape.com/static/oscar/favicon.ico
http://books.toscrape.com/static/oscar/css/styles.css
http://books.toscrape.com/static/oscar/js/bootstrap-datetimepicker/bootstrap-datetimepicker.css
http://books.toscrape.com/static/oscar/css/datetimepicker.css

javascript_files.txt

http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
http://books.toscrape.com/static/oscar/js/bootstrap3/bootstrap.min.js
http://books.toscrape.com/static/oscar/js/oscar/ui.js
http://books.toscrape.com/static/oscar/js/bootstrap-datetimepicker/bootstrap-datetimepicker.js
http://books.toscrape.com/static/oscar/js/bootstrap-datetimepicker/locales/bootstrap-datetimepicker.all.js

好的,最后,我鼓励你进一步扩展此代码以构建一个复杂的审计工具,该工具能够识别不同的文件、它们的大小,并可能提出优化网站的建议!

作为挑战,尝试下载所有这些文件并将它们存储在本地磁盘中(本教程可以提供帮助)。

我有另一个教程向你展示如何提取所有网站链接,请在此处查看。

此外,如果你正在分析的网站不小心禁止了你的 IP 地址,则在这种情况下你需要使用代理服务器。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: