张贴表格,然后下载其他网页

Post form and then download other webpage

本文关键字:其他 网页 下载 然后 表格 张贴      更新时间:2023-09-26

我想开发一个能做两件事的工具:

  1. 设置以下web表单的语言和日期:http://ibreviary.com/m2/opzioni.php,然后

  2. 在同一网站上下载不同页面的文本,但保留这些设置。例如http://ibreviary.com/m2/breviario.php?s=lodi.

该工具应该模仿用户正常浏览这些页面时的操作:设置所需的语言和日期,然后查看动态创建的页面。

我认为Node.js会是一个很好的工具。尽管我能够让它发布表单数据(我想),然后下载所需的页面,但我无法让服务器"记住"设置(就像在真实的网络浏览器会话中一样)。下载的文本始终是默认文本(今天的日期)。

以下是我迄今为止拥有的Javascript代码:

var FormData = require('form-data');
var request = require('request');
var http = require('http');
var fs = require('fs');
var formData = {
  lang: 'en',
  giorno: 15,
  mese: 11,
  anno: 2014
};
request.post({url:'http://www.ibreviary.com/m/opzioni.php',
              formData: formData},
             function optionalCallback(err, httpResponse, body) {
    if (err) {
      return console.error('upload failed:', err);
    }
  console.log('Upload successful!  Server responded with:', body);
  download(url, destination, function(){
    console.log("Done saving file '" + destination +
                "' downloaded from '" + url + "'");
  });
});
var url = "http://www.ibreviary.com/m/breviario.php?s=lodi";
var destination = "file.html";
var download = function(url, destination, callback) {
  var file = fs.createWriteStream(destination);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(callback);  // close() is async, call callback
                             // after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(destination); // Delete the file async.
    if (callback) callback(err.message);
  });
};

如果你尝试一下,你会看到第一个request.post的输出是未更改的网页:就好像表单的发布不起作用一样。

有什么想法吗?

最后,我使用Python的mechanize包来完成我想要的任务。

以下是对我有效的最低工作示例:

#!/usr/bin/python
import re
import mechanize
optionsURI = "http://www.ibreviary.com/m2/opzioni.php"
hourURI = "http://www.ibreviary.com/m2/breviario.php?s=lodi"
br = mechanize.Browser()
# Open the options form and submit the desired data.
br.open(optionsURI)
br.select_form(nr=0)        # Select the first (and only) form on the page.
br.form["anno"] = "2014"    # year
br.form["mese"] = ["11"]    # month
br.form["giorno"] = "15"    # day
br.form["lang"] = ["en"]    # language or rite:
                            #   it, en, es, fr, pt, ro, ar, ra, la, vt
br.submit()
# Open the desired page and print to standard output.
mypage = br.open(hourURI)
print mypage.read()