如何使用python在chrome浏览器上点击下载图标

2024-04-26 18:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过点击Chrome浏览器上的下载图标来下载文件。 我尝试了几种方法,比如Xpath和CSS,但都不起作用。请让我知道是否有任何解决方案,在这方面使用Python3.x和硒。你知道吗

下面是我尝试过的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

class TEAutomation:

    def automateTask(self):
        chromeOptions = Options()
        chromeOptions.add_experimental_option("prefs",{"download.default_directory": "/home/vishal/Documents/PythonProgram/"})

        baseUrl = "https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Customer+Drawing%7F160743%7FM2%7Fpdf%7FEnglish%7FENG_CD_160743_M2.pdf%7F160743-1"
        driver = webdriver.Chrome(executable_path="/home/vishal/PycharmProjects/VSProgramming/drivers/chromedriver",chrome_options=chromeOptions)
        driver.maximize_window()
        driver.get(baseUrl)
        driver.implicitly_wait(10)

        driver.find_element(By.XPATH,'//*[@id="download"]').click()
        #driver.find_element(By.CSS_SELECTOR, '#download').click()

        time.sleep(5)
        driver.quit()

molexAuto = TEAutomation()
molexAuto.automateTask()

先谢谢你。你知道吗


Tags: fromimportbytimedownloaddriverseleniumchrome
1条回答
网友
1楼 · 发布于 2024-04-26 18:56:04

当您尝试单击该元素时,可能该元素仍未加载,请尝试使用WebDriverWait等待它,我没有chrome,因此您必须自己进行测试:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

class TEAutomation:

    def automateTask(self):
        chromeOptions = Options()
        prefs = {
            "download.default_directory": "/home/vishal/Documents/PythonProgram/",
            "plugins.always_open_pdf_externally": True
        }
        chromeOptions.add_experimental_option("prefs", prefs)

        baseUrl = "https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Customer+Drawing%7F160743%7FM2%7Fpdf%7FEnglish%7FENG_CD_160743_M2.pdf%7F160743-1"
        driver = webdriver.Chrome(executable_path="/home/vishal/PycharmProjects/VSProgramming/drivers/chromedriver",chrome_options=chromeOptions)
        driver.implicitly_wait(10)
        driver.maximize_window()
        driver.get(baseUrl)

        time.sleep(5)
        driver.quit()

molexAuto = TEAutomation()
molexAuto.automateTask()

相关问题 更多 >