Php:设置文本框值,模拟按钮点击并读取返回的数据


Php: set textbox value, simulate a button click and read the data returned

我正在尝试从php站点收集一些数据。然而,这个特定的 php 页面已经使用自己的函数(下面的代码中的 setReport() )将$POST数据(转换为我无法复制的特殊时间戳数据)并发送到其服务器。因此,为了获得这些数据,请在文本框中输入库存号,然后按下按钮是我猜的唯一方法。

以下是我想从中获取数据的 php 站点源代码的片段。

http://www.gretai.org.tw/ch/stock/statistics/monthly/st42.php

> <form name="search" method="post" action="st42.php"> <table
> width="736" border="0" cellpadding="0" cellspacing="0" summary="查詢">  
> .......    
>          <td class="search-in02">股票代碼:
> 
>           <input id="input_stock_code" name="input_stock_code"
> class="input01" size="6" maxlength="6">
> 
>             <A HREF="#" onclick="ChoiceStkCode(document.getElementById('input_stock_code'));"
> onkeypress="ChoiceStkCode(document.getElementById('input_stock_code'));"
> class="page_table-text_over">代碼查詢</A>                
> 
>             &nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="input01" value="查詢" onclick="query()" onkeypress="query()"/>       
> ........
> 
> </table>
> 
> </form>                   function query(){               
> 
>       var code = document.getElementsByName("input_stock_code")[0].value;
> 
>       var param = 'ajax=true&input_stock_code='+code;
> 
>       setReport('result_st42.php',param );        
> 
>   }

我正在考虑编写一个PHP代码,以下步骤来获取数据。但我不知道如何执行第 2 步。有没有每个人都可以在这方面提供帮助?还是有另一种方法可以做到这一点?非常感谢!!

  1. 使用curl_init在网站中阅读。
  2. 设置文本框,"input_stock_code"与值并模拟按钮单击。
  3. 解析来自 curl_exec() 的结果。

我无法真正测试这一点,因为我无法阅读该网站 - 但是与其获取页面,填写表单并获得结果,不如直接通过转到

http://www.gretai.org.tw/ch/stock/statistics/monthly/result_st42.php?ajax=true&input_stock_code=<code>

setReport() 所做的时间戳业务只是为了阻止浏览器加载缓存的结果,因此您可以毫无问题地省略它。

编辑:更正,您确实需要发布ajax并input_stock_code变量。您可以使用 CURL 在 PHP 中执行此操作:

// Build URL complete with timestamp
$url = 'http://www.gretai.org.tw/ch/stock/statistics/monthly/result_st42.php?timestamp='.time().'156';
// POST body variables
$fields = array(
            'ajax'=>urlencode('true'),
            'input_stock_code'=>urlencode('1158')
        );
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
// Pretend we are a browser that is looking at the site
curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20120403211507 Firefox/12.0');
curl_setopt($ch,CURLOPT_REFERER, 'http://www.gretai.org.tw/ch/stock/statistics/monthly/st42.php');
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;

基于本网站上的摘要帖子。