python – Selenium webdriver在chrome:// downloads中找不到元素

我在Python中使用了硒与chromedriver.

我的问题是,当我尝试访问chrome下载页面上的元素时,selenium会给我一个错误(chrome:// downloads).
例如,我尝试获取文件URL“http://file.jpg”.

<a id="url" target="_blank" href="http://file.jpg">http://file.jpg</a>

但是当我尝试通过它的id获取元素时,我得到一个例外.

码:

driver = webdriver.Chrome("chromedriver.exe")
driver.get("chrome://downloads/")
file_url = driver.find_element_by_id("url").get_attribute("href")

例外:

Traceback (most recent call last):
  File "<pyshell#34>", line 3, in <module>
    driver.find_element_by_id("url")
  File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 269, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
    'value': value})['value']
  File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "D:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"url"}
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)

通过driver.execute_script()使用javascript对我来说也不起作用.
当我在浏览器中看到元素时,为什么我会收到NoSuchElementException?

最佳答案
目标链接位于多个阴影根块内.试试这个:

driver = webdriver.Chrome("chromedriver.exe")
driver.get("chrome://downloads/")

manager = driver.find_element_by_css_selector('body/deep/downloads-manager')
item = manager.find_element_by_css_selector('body/deep/downloads-item')
shadow = driver.execute_script('return arguments[0].shadowRoot;', item)
link = shadow.find_element_by_css_selector('div#title-area>a')

file_url = link.get_attribute("href")

转载注明原文:python – Selenium webdriver在chrome:// downloads中找不到元素 - 代码日志