我正在运行 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()
最佳答案
我从未使用过 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,您可以从那里打开该文件
关于python - Selenium 未定位 xpath 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999652/