Selenium没有找到xpath元素

时间:2017-12-27 23:06:04

标签: python selenium xpath selenium-chromedriver

我正在运行Selenium下载示例PdF文件并在Chrome中打开它但由于某种原因,我无法让Selenium点击下载部分中的第一个结果。

已经指定了XPath,但它只是没有点击该元素,由于超时错误(下面),该过程就被中止了。拜托,有没有人对我做错了什么有任何想法?

======================================================================
ERROR: testSearch (__main__.InitialSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/Josh/PycharmProjects/ideqcomps/test.py", line 33, in testSearch
    lambda driver: driver.find_elements_by_xpath(downloaded_file_XPath))
  File "/Users/Josh/Library/Python/3.6/lib/python/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 


----------------------------------------------------------------------
Ran 1 test in 24.415s

FAILED (errors=1)

Process finished with exit code 1

以下是我正在运行的代码:

from selenium import webdriver

from selenium.webdriver.support.ui import WebDriverWait

import unittest


class InitialSearch(unittest.TestCase):

    def setUp(self):
        options     = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(chrome_options=options)
        self.driver.get("https://wetransfer.com/downloads/5451e039a782938826861676664ae91a20171227191356/a45960")

    def testSearch(self):
        driver                   = self.driver
        download_button_xpath    = '//*[@id="file-link"]'
        agree_xpath              = '//*[@id="5451e039a782938826861676664ae91a20171227191356"]/div/div[2]/button'
        downloaded_file_xpath    = '//*[@id="downloads-list"]/downloads-item[1]'
    # Click on agree to terms button
        agree_element = WebDriverWait(driver, 10).until(
            lambda driver: driver.find_element_by_xpath(agree_xpath))
        agree_element.click()
    # Click on download button
        download_button_element = WebDriverWait(driver, 10).until(
            lambda driver: driver.find_element_by_xpath(download_button_xpath))
        download_button_element.click()
    # Go to downloads
        self.driver.get("chrome://downloads/")
    # Click on first item in downloads
        open_pdf_element = WebDriverWait(driver, 10).until(
            lambda driver: driver.find_element_by_xpath(downloaded_file_xpath))
        open_pdf_element.click()


if __name__ == '__main__':
    unittest.main()

1 个答案:

答案 0 :(得分:1)

我从未使用过selenium点击chrome:// downloads /中的元素,我不知道是否可以。我会把它留给这里的专家。

话虽如此,如果您最终改变了打开下载的pdf的方式,您可以尝试以下方法

options = webdriver.ChromeOptions()
options .add_experimental_option("prefs", {
    "download.default_directory": '<temp_download_dir>',
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
})

这将迫使chrome将pdf下载到temp_download_dir,从那里你可以打开文件