首页 > 解决方案 > 查找可能的 URL 参数

问题描述

我正在尝试用 Ruby/Mechanize 编写一个网络爬虫。我试图实现的一件事是一个可以找到潜在 URL 参数的函数。这是一个片段:

require 'mechanize'
def find_parameters(url)
    mechanize = Mechanize.new
    result = []
    # build list of potential parameters at URL
    result # return
end

想象一下在 URL 中发送传递http://example.com/。上面example.com有一个index.php文件,它接受 URL 参数调用baz,并将该参数的值打印到页面。

<?php
    if (isset($_GET['baz'])) {
        echo $_GET['baz'];
    }
?>

因此http://example.com?baz=123将转到打印的页面123。我们知道查看baz作为潜在参数的源代码,有没有办法让 Mechanize 找到所有潜在参数并返回它们的列表?

前任:find_parameters('http://example.com/') => ['baz']

标签: phprubymechanize

解决方案


您可以调整字符串:

require 'mechanize'
def find_parameters(url)
  mechanize = Mechanize.new
  result = []
  mechanize.get(url)  #go to the page
  # get the current page, split in the possible parameters list, split by parameters
  # (rescue in case there are no params)
  ( mechanize.page.uri.to_s.split("?")[1].split("&") rescue []).each do |key_val| 
    # split the pair of param and value, and store the param name
    result << key_val.split("=")[0]
  end
  return result
end

推荐阅读