Selenium:如何使用firefox和python禁用图像加载?

2024-05-12 14:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过类似的问题,一个应该是答案,但当我尝试它只给出了一个部分的解决方案。

我指的是这个问题:Disable images in Selenium Python

我的问题是,我尝试了该解决方案,但有些图像并没有出现,而是来自:

<img href="www.xxx.png"> 

正在加载。 有没有办法告诉firefox/selenium不要这么做? 如果不是,有没有办法从我返回的dom元素中丢弃它,通过

self._browser.get(url)
content=self._browser.page_source

例如,在dom树上执行某种find-replace?

浏览器配置与上一个问题中的浏览器相同:

    firefox_profile = webdriver.FirefoxProfile()
    # Disable CSS
    firefox_profile.set_preference('permissions.default.stylesheet', 2)
    # Disable images
    firefox_profile.set_preference('permissions.default.image', 2)
    # Disable Flash
    firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
    # Set the modified profile while creating the browser object
    self._browser = webdriver.Firefox(firefox_profile=firefox_profile)

—————————————————————————————————————————————————————————————————————— 我一直在挖掘,我学到的是,
如果我检查selenium/firefox组合所看到的文本文档,它不会带来图像,然后作为链接保存。

但当我这么做的时候:

self._browser.save_screenshot("info.png") 

我有一个24兆的文件,所有的img链接都已加载。
有人能给我解释一下这件事吗?
谢谢


Tags: 图像selfbrowserimgpngseleniumfirefox解决方案
1条回答
网友
1楼 · 发布于 2024-05-12 14:21:45

可以使用以下代码禁用图像:

firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference('permissions.default.image', 2)
firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')

driver = webdriver.Firefox(firefox_profile=firefox_profile)

如果你需要阻止某个特定的url。。。嗯。。。 我认为您需要添加字符串:

127.0.0.1 www.someSpecificUrl.com 

在测试开始前删除hosts文件,并在测试完成后删除它。

相关问题 更多 >