【问题标题】:How to automate downloading a file from a site?如何自动从站点下载文件?
【发布时间】:2019-06-14 04:04:27
【问题描述】:

我想从这个网址下载几个数据文件:https://pselookup.vrymel.com/

该站点包含一个日期字段和一个下载按钮。我想下载多年的数据(这意味着很多请求),我想自动下载。

我创建了一个 Javascript sn-p,但是,它会一遍又一遍地下载相同的文件。

$dateField = document.getElementsByClassName('csv_download_input__Input-encwx-1 dDiqPH')[2]

$dlButton = document.getElementsByClassName('csv_download_input__Button-encwx-0 KLfyv')[2]

var now = new Date();
var daysOfYear = [];
for (var d = new Date(2016, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
    daysOfYear.push(new Date(d).toISOString().substring(0,10));
}

(function theLoop (i) {
  setTimeout(function () {
    $dlButton.click()
    $dateField.value = daysOfYear[i]
    if (--i) {          // If i > 0, keep going
      theLoop(i);       // Call the loop again, and pass it the current value of i
    }
  }, 3000);
})(daysOfYear.length-1);

如何自动下载所有文件?

【问题讨论】:

    标签: javascript download automation


    【解决方案1】:

    首先,客户端中的 javascript 可能不是执行此操作的最佳语言,也不是实现此操作的最佳方法。它可能有效,但在选择解决问题的方法时最好知道什么是最好的。此外,它将避免您在接受下载的弹出窗口中单击约 800 次。

    您可以通过编程方式获取文件,只需了解您的浏览器正在做什么来获取文件并尝试成堆复制它。

    检查调用后,您可以看到它正在调用端点,并且该端点正在返回一个链接,其中包含您可以下载的文件。

    嗯,这很容易,所以现在您只需使用任何语言制作脚本即可检索它们。

    我选择了javascript,但不是客户端,而是nodejs,这意味着它必须从您的计算机上运行。

    您可以对bashpython 或任何其他语言执行相同的操作。

    要运行它,请执行以下操作:

    • 转到一个新的空目录
    • 运行npm install axios
    • 用我粘贴的代码创建一个文件,我们称之为crawler.js
    • 运行node crawler.js

    这已经使用node v8.15.0进行了测试

    // NOTE: Require this to make a request and save the link as file 20190813:Alevale
    const axios = require('axios');
    const fs = require('fs');
    
    let now = new Date();
    let daysOfYear = [];
    const baseUrl = 'https://a4dzytphl9.execute-api.ap-southeast-1.amazonaws.com/prod/eod/'
    
    for (var d = new Date(2016, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
        daysOfYear.push(new Date(d).toISOString().substring(0,10));
    }
    
    const waitFor = (time) => {
        return new Promise((resolve => setTimeout(resolve, time)))
    }
    
    const getUrls = async () =>{
        let day
        for (day of daysOfYear) {
            console.log('getting day', baseUrl + day)
            // NOTE: Throttle the calls to not overload the server 20190813:Alevale
            await waitFor(4000)
    
            await axios.get(baseUrl + day)
                .then(response => {
                    console.log(response.data);
                    console.log(response);
                    if (response.data && response.data.download_url) {
                        return response.data.download_url
                    }
                    return Promise.reject('Could not retrieve response.data.download_url')
                })
                .then((url) =>{
                    axios({
                        method: 'get',
                        url,
                        responseType: 'stream'
                    })
                        .then(function (response) {
                            // NOTE: Save the file as 2019-08-13 20190813:Alevale
                            response.data.pipe(fs.createWriteStream(`${day}.csv`))
                        })
                        .catch(console.error)
    
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }
    
    getUrls()
    

    【讨论】:

    • 像魅力一样工作!谢谢!
    【解决方案2】:

    您可以从以下位置获取下载链接,而不是模拟用户: https://a4dzytphl9.execute-api.ap-southeast-1.amazonaws.com/prod/eod/2019-08-07 只需将末尾的日期更改为您要下载的文件的日期即可。并使用 axios 来获取这个 URL。

    这将为您节省一些时间(以防您真的不需要模拟用户的点击等)

    然后你会得到这样的响应:

    {
       download_url":"https://d3u9ukmkxau9he.cloudfront.net/eod/2019-08-07.csv?Expires=1566226156&Signature=QRUk3tstuNX5KYVPKJSWrXsSXatkWS-eFBIGUufaTEMJ~rgpVi0iPCe1AXl5pbQVdBQxOctpixCbyNz6b9ycDgYNxEdZqPr2o2pDe8cRL655d3zXdICnEGt~dU6p35iMAJkMpPSH~jbewhRSCPUwWXQBfOiEzlHwxru9lPnDfsdSnk3iI3GyR8Oc0ZP50EdUMHF7MjWSBRbCIwnu6wW4Jh0bPmZkQDQ63ms5QxehsmtuGLOgcrC6Ky1OffVQj~ihhmBt4LGhZTajjK4WO18hCP3urKt03qpC4bOvYvJ3pxvRkae0PH1f-vbTWMDkaWHHVCrzqZhkAh3FlvMTWj8D4g__&Key-Pair-Id=APKAIAXOVAEOGN2AYWNQ"
    }
    
    and then you can use axios to GET this url and download your file.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2011-06-23
      • 2016-07-09
      • 1970-01-01
      • 2022-01-22
      • 2020-11-23
      • 2022-06-18
      • 1970-01-01
      相关资源
      最近更新 更多