无法通过Xpath为chrome下载页面找到元素



我正在尝试编写代码来检查selenium和chrome驱动程序是否完成了下载。我的想法是

1.转到下载页面("chrome://downloads/"(

2.检查url以确保我们已经从该网站下载了文件(定位http://xxxxxxxx)

3.检查下载状态(如果我发现"显示在文件夹中",则意味着下载成功。如果没有,则下载失败(

当我试图定位url时,我陷入了第二步。我使用开发人员工具,将光标移动到url以定位元素,然后右键单击并复制xpath。xpath就像这个

//*[@id="file-link"]

然后我尝试在开发者工具中单击ctrl+F,然后再次粘贴xpath。我找不到元素。为什么?已选中没有框架。

它隐藏DOM,需要使用CSS选择器选择/deep/

downloads-manager/deep/downloads-item/deep/a[id="file-link"]

另一种方法是使用File class为其编写一个小型Java实用程序。类似这样的东西:

File f = new File("C:\Users\username\Downloads\Users_" + fielName+ ".xls");
Assert.assertTrue(f.exists());

这在Python:中适用

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
# disable file preview
options = webdriver.ChromeOptions()
options.add_experimental_option(
'prefs', {
'profile.default_content_settings.popups': 0,
'download.default_directory': '/some/download/dir',
'download.prompt_for_download': False,
'download.directory_upgrade': True,
'plugins.always_open_pdf_externally': True,
'plugins.plugins_disabled': 'Chrome PDF Viewer',
'disable-popup-blocking': True
}
)
driver = webdriver.Chrome(options=options)
# start load file
driver.get('url-to-file')

def condition_load_file(dr: webdriver.Chrome):
return dr.execute_script("""
try {
var el = document.querySelector("body > downloads-manager").shadowRoot.querySelector("#frb0").shadowRoot.querySelector("#show");
return el !== null;
} catch(exc) {
return false;
}
""")

# open new window and go to chrome://downloads/
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get('chrome://downloads/')
# waiting for download to finish
WebDriverWait(driver, 120).until(condition_load_file)

最新更新