我需要访问此页面 chrome://downloads/ 并检查文件是否已下载,但它是 Shadow DOM。
我发现这篇文章如何使用 Selenium Webdriver 访问 DOM 元素。http://jeremysklarsky.github.io/blog/2015/06/13/accessing-shadow-dom-elements-with-selenium-webdriver/
但这是用JS写的
driver.executeScript("return $('body /deep/ <#yourSelector>')")
driver.executeScript("return $('body /deep/ ._mm_column')[0].textContent").then(function(title){
title.should.contain(segmentName);
});
将其更改为 Watir 语法后,我的代码可以工作,但没有返回所需的结果:
execute_script("return $('<#file-link>')")
execute_script("return $( '<:contains(test-file.mp3)>')")
我刚刚在控制台中得到 nils。
在此输入图像描述
但我想要的是确保该元素存在。
正如 titusfortner 删除的答案中提到的,Selenium Easy 有一篇相关文章,“使用 Webdriver 处理 Shadow DOM 元素”。事实证明,您可以通过 JavaScript 获取影子元素,然后像平常一样与其后代进行交互。
然而,由于 Watir 的编写方式,我不得不进行猴子补丁Watir::Browser
使其发挥作用。我会看看是否可以获得更永久的修复,但现在,这是一个有效的示例:
require 'watir'
# Monkey-patch due to being unable to check the tag name of the shadow root
class Watir::Browser
def wrap_element(scope, element)
Watir.element_class_for(element.tag_name.downcase).new(scope, element: element)
rescue Selenium::WebDriver::Error::UnknownError # need a better rescue
Watir::Element.new(scope, element: element)
end
end
def expand_root_element(element, browser)
browser.execute_script("return arguments[0].shadowRoot", element)
end
browser = Watir::Browser.new
# Create a download item
browser.goto('https://chromedriver.storage.googleapis.com/2.33/chromedriver_win32.zip')
browser.goto('chrome://downloads')
# Navigate the shadow DOM to the download items
download_manager = browser.element(css: 'downloads-manager')
shadow_download_manager = expand_root_element(download_manager, browser)
download_items = shadow_download_manager.elements(css: '#downloads-list downloads-item')
shadow_download_items = download_items.map { |s| expand_root_element(s, browser) }
# Find a specific download item by file name
expected_file = /chromedriver_win32/
download = shadow_download_items.find { |s| s.span(id: 'name').text_content =~ expected_file }
# Do something with the download - eg wait for the download to complete
download.link(id: 'show').wait_until_present
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)