首页 > 解决方案 > Selenium Python - 获取所有已加载 URL 的列表(图像、脚本、样式表等)

问题描述

当谷歌浏览器通过 Selenium 加载网页时,它可能会加载页面所需的其他文件,例如 from<img src="example.com/a.png"><script src="example.com/a.js">tags。此外,CSS 文件。

如何获取浏览器加载页面时下载的所有 URL 的列表?(以编程方式,在 Python 中使用 Selenium 和 chromedriver)也就是说,Chrome 中开发人员工具的“网络”选项卡中显示的文件列表(显示下载文件的列表)。

使用 Selenium、chromedriver 的示例代码:

from selenium import webdriver
options = webdriver.ChromeOptions()
options.binary_location = "/usr/bin/x-www-browser"
driver = webdriver.Chrome("./chromedriver", chrome_options=options)
# Load some page
driver.get("https://example.com")
# Now, how do I see a list of downloaded URLs that took place when loading the page above?

标签: pythonseleniumselenium-webdriverselenium-chromedriver

解决方案


您可能想查看 BrowserMob 代理。它可以捕获 Web 应用程序的性能数据(通过 HAR 格式),以及操纵浏览器行为和流量,例如将内容列入白名单和黑名单、模拟网络流量和延迟,以及重写 HTTP 请求和响应。

取自readthedocs,用法简单,与selenium webdriver api很好地集成。您可以在此处阅读有关 BMP的更多信息。

from browsermobproxy import Server
server = Server("path/to/browsermob-proxy")
server.start()
proxy = server.create_proxy()

from selenium import webdriver
profile  = webdriver.FirefoxProfile()
profile.set_proxy(proxy.selenium_proxy())
driver = webdriver.Firefox(firefox_profile=profile)


proxy.new_har("google")
driver.get("http://www.google.co.uk")
proxy.har # returns a HAR JSON blob

server.stop()
driver.quit()

推荐阅读