Selenium:Chrome浏览器自动加载Flash

在自动化脚本编写过程中,遇到一些网页需要使用Flash插件,但是通过Selenium启动的浏览器不能默认对网页启动Flash,需要在chrome://settings/content/siteDetails?site={url}网页进行设置。

添加argument:--allow-outdated-plugins

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
    chrome_options = Options()
    chrome_options.add_argument('--allow-outdated-plugins')
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(http://testops:81/phpwind/register.php#breadCrumb)

参数作用:允许使用旧版本的插件。
注意:旧版本的插件可能有漏洞,不要访问来历不明的网站。

允许Falsh方法

from urllib.parse import quote_plus as url_quoteplus
from urllib.parse import urlsplit
from selenium.webdriver.common.by import By as WebBy
from selenium.webdriver.support.ui import Select as WebSelect


def allow_flash(driver, url):
    def _base_url(url):
        if url.find("://") == -1:
            url = "http://{}".format(url)
        urls = urlsplit(url)
        return "{}://{}".format(urls.scheme, urls.netloc)

    def _shadow_root(driver, element):
        return driver.execute_script("return arguments[0].shadowRoot", element)

    base_url = _base_url(url)
    driver.get("chrome://settings/content/siteDetails?site={}".format(url_quoteplus(base_url)))

    root1 = driver.find_element(WebBy.TAG_NAME, "settings-ui")
    shadow_root1 = _shadow_root(driver, root1)
    root2 = shadow_root1.find_element(WebBy.ID, "container")
    root3 = root2.find_element(WebBy.ID, "main")
    shadow_root3 = _shadow_root(driver, root3)
    root4 = shadow_root3.find_element(WebBy.CLASS_NAME, "showing-subpage")
    shadow_root4 = _shadow_root(driver, root4)
    root5 = shadow_root4.find_element(WebBy.ID, "advancedPage")
    root6 = root5.find_element(WebBy.TAG_NAME, "settings-privacy-page")
    shadow_root6 = _shadow_root(driver, root6)
    root7 = shadow_root6.find_element(WebBy.ID, "pages")
    root8 = root7.find_element(WebBy.TAG_NAME, "settings-subpage")
    root9 = root8.find_element(WebBy.TAG_NAME, "site-details")
    shadow_root9 = _shadow_root(driver, root9)
    root10 = shadow_root9.find_element(WebBy.ID, "plugins")  # Flash
    shadow_root10 = _shadow_root(driver, root10)
    root11 = shadow_root10.find_element(WebBy.ID, "permission")
    WebSelect(root11).select_by_value("allow")

设置driver允许Flash

allow_flash(driver,"http://testops:81")

解释

shadow root elements

该种类elements下的元素,不能通过selenium方法直接定位,需要JS的方法:element.shadowRoot找到元素

版本

在Chrome73.0.3683.86上测试成功,旧版本的Chrome不一定需要这么麻烦,添加一个argument也许就可以了。

posted @ 2021-04-21 17:34  Feng1024  阅读(210)  评论(0编辑  收藏  举报