Python - 选择"保存链接为"并使用Selenium保存文件

时间:2016-08-29 08:14:52

标签: python selenium

新手:网页上有不同的文件,可以按如下方式下载: 1.右键单击文件链接 2.选择"保存链接为" 3.单击"保存"新窗口上的按钮。

我尝试了以下代码(前两个步骤),但它无效:

    from selenium import webdriver
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.keys import Keys
    import time

    driver = webdriver.Chrome()
    driver.maximize_window() 

    driver.get('www.example.com')
    time.sleep(1)

    driver.find_element_by_link_text("MarketFiles/").click()


    actionChains = ActionChains(driver)

    download_file = "Market_File1.csv"
    link = driver.find_element_by_link_text(download_file)

    actionChains.context_click(link).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN).perform();

请建议如何使用这3个步骤下载文件。感谢

2 个答案:

答案 0 :(得分:0)

保存链接将打开无法通过selenium直接控制的系统对话框。

话虽如此,可以在配置文件中配置下载首选项,可以在启动浏览器时使用,在这种情况下,任何点击下载都会根据Chrome配置文件中的首选项保存文件

chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "/some/path"}
chromeOptions.add_experimental_option("prefs",prefs)
chromedriver = "path/to/chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)

参考:https://sites.google.com/a/chromium.org/chromedriver/capabilities

答案 1 :(得分:0)

根据java,您可以使用以下代码单击“保存为链接”,然后单击“在新窗口中保存”

try {
          Robot bot = new Robot();
            //location of link on your page
            bot.mouseMove(5, 12);    
            //instigate right click of mouse
            bot.mousePress(InputEvent.BUTTON1_MASK);
            bot.mouseRelease(InputEvent.BUTTON1_MASK);
            Thread.sleep(1000); 
            /*repeatedly press down arrow untill you reach save as link in context menu*/
            bot.keyPress(KeyEvent.VK_DOWN);
            Thread.sleep(1000);
            bot.keyPress(KeyEvent.VK_DOWN);
            Thread.sleep(1000);
            bot.keyPress(KeyEvent.VK_DOWN);
            Thread.sleep(1000);
            bot.keyPress(KeyEvent.VK_DOWN);
           //press enter to select save as link
            Thread.sleep(1000);
            //press enter to press save button on new window
            bot.keyPress(KeyEvent.VK_ENTER);                
            Thread.sleep(1000);
            bot.keyPress(KeyEvent.VK_ENTER);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

根据您的问题,您需要python代码,以便您可以使用此链接https://pypi.python.org/pypi/py_robot/0.1

在python中转换此代码