如何自动化从网站下载文件?

6
我想从以下网址下载多个数据文件: https://pselookup.vrymel.com/ 该网站包含日期字段和下载按钮。我想要下载多年的数据(这意味着会有很多请求),并且希望自动化完成。
我创建了一个Javascript片段,但它一直在重复下载同一个文件。
$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);

如何自动下载所有文件?
2个回答

7
首先,使用客户端的javascript可能不是最好的语言来实现这个目标,也不是解决问题的最佳方案。它可能可行,但最好知道在选择方法时什么是最好的。此外,这样可以避免您点击800次弹出窗口以接受下载。
您可以通过学习浏览器获取文件的方式并尝试以批量方式复制它来以编程方式获取文件。
检查调用后,您可以看到它正在调用一个端点,该端点返回包含您可以下载的文件的链接。
好吧,这很容易,所以您现在只需要制作任何语言的脚本以能够检索它们。
我选择了javascript,但不是客户端,而是nodejs,这意味着它必须从您的计算机运行。
您可以使用bash、python或任何其他语言完成相同的操作。
要运行此操作,请执行以下操作:
- 转到新的空目录 - 运行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()

0

你可以通过获取下载链接而不是模拟用户来下载文件: https://a4dzytphl9.execute-api.ap-southeast-1.amazonaws.com/prod/eod/2019-08-07 只需更改链接末尾的日期以获取所需下载文件对应的日期,并使用axios访问此链接。

这样可以节省您的时间(如果您确实不需要模拟用户点击等操作)。

然后,您将会得到以下类型的响应:

{
   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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接