2009-07-17 89 views
7

我想创建一个程序,将一个字符串输入到像Google这样的网站上的文本框(不使用他们的公共API),然后提交表单并获取结果。这可能吗?抓取结果将需要使用我假设的HTML抓取,但是如何将数据输入到文本字段并提交表单?我会被迫使用公共API吗?像这样的东西只是不可行?我需要找出查询字符串/参数吗?如何在不使用API​​的情况下以编程方式执行搜索?

谢谢

回答

4

理论

我会做的是创建一个小程序,可以任何形式的数据自动提交到任何地方,回来的结果。在Java中使用HTTPUnit很容易。任务如下:

  • 连接到Web服务器。
  • 解析页面。
  • 获取页面上的第一个表单。
  • 填写表格数据。
  • 提交表单。
  • 读取(并解析)结果。

你选择将取决于多种因素,包括解决方案:

  • 您是否需要效仿的JavaScript
  • 你需要的数据来做事后
  • 什么语言有什么这是你精通
  • 应用程序的速度(这是一个查询或100,000?)
  • 应用程序需要多久工作
  • 这是一次性的,还是需要维护?

例如,你可以试试下面的应用程序提交数据给你:

然后grep(AWK或sed的)生成的网页。

屏幕抓取是下载示例HTML文件并在vi(或VIM)中手动解析它的另一个技巧。将击键保存到文件中,然后在运行查询时,将这些击键应用于生成的网页以提取数据。这种解决方案不可维护,也不可100%可靠(但很少从网站上截取屏幕)。它工作,而且速度很快。

一个半通用的Java类提交网站的形式(具体抓,登录到网站)低于在希望,这可能是有用的。不要将它用于邪恶。

import java.io.FileInputStream; 

import java.util.Enumeration; 
import java.util.Hashtable; 
import java.util.Properties; 

import com.meterware.httpunit.GetMethodWebRequest; 
import com.meterware.httpunit.SubmitButton;  
import com.meterware.httpunit.WebClient;   
import com.meterware.httpunit.WebConversation;  
import com.meterware.httpunit.WebForm;    
import com.meterware.httpunit.WebLink;    
import com.meterware.httpunit.WebRequest;   
import com.meterware.httpunit.WebResponse;   

public class FormElements extends Properties 
{           
    private static final String FORM_URL = "form.url"; 
    private static final String FORM_ACTION = "form.action"; 

    /** These are properly provided property parameters. */ 
    private static final String FORM_PARAM = "form.param."; 

    /** These are property parameters that are required; must have values. */ 
    private static final String FORM_REQUIRED = "form.required.";    

    private Hashtable fields = new Hashtable(10); 

    private WebConversation webConversation; 

    public FormElements() 
    {      
    }      

    /** 
    * Retrieves the HTML page, populates the form data, then sends the 
    * information to the server.          
    */                 
    public void run()             
    throws Exception             
    {                 
    WebResponse response = receive();         
    WebForm form = getWebForm(response);       

    populate(form); 

    form.submit(); 
    }    

    protected WebResponse receive() 
    throws Exception    
    {        
    WebConversation webConversation = getWebConversation(); 
    GetMethodWebRequest request = getGetMethodWebRequest(); 

    // Fake the User-Agent so the site thinks that encryption is supported. 
    //                  
    request.setHeaderField("User-Agent",         
     "Mozilla/5.0 (X11; U; Linux i686; en-US; rv\\:1.7.3) Gecko/20040913"); 

    return webConversation.getResponse(request); 
    }            

    protected void populate(WebForm form) 
    throws Exception      
    {          
    // First set all the .param variables. 
    //          
    setParamVariables(form);    

    // Next, set the required variables. 
    //         
    setRequiredVariables(form);  
    }          

    protected void setParamVariables(WebForm form) 
    throws Exception        
    {            
    for(Enumeration e = propertyNames(); e.hasMoreElements();) 
    {               
     String property = (String)(e.nextElement());    

     if(property.startsWith(FORM_PARAM)) 
     {          
     String fieldName = getProperty(property); 
     String propertyName = property.substring(FORM_PARAM.length()); 
     String fieldValue = getField(propertyName);     

     // Skip blank fields (most likely, this is a blank last name, which 
     // means the form wants a full name).        
     //                 
     if("".equals(fieldName))          
      continue;               

     // If this is the first name, and the last name parameter is blank, 
     // then append the last name field to the first name field.   
     //                 
     if("first_name".equals(propertyName) &&       
      "".equals(getProperty(FORM_PARAM + "last_name")))   
      fieldValue += " " + getField("last_name");      

     showSet(fieldName, fieldValue); 
     form.setParameter(fieldName, fieldValue); 
     }            
    }            
    }             

    protected void setRequiredVariables(WebForm form) 
    throws Exception         
    {             
    for(Enumeration e = propertyNames(); e.hasMoreElements();) 
    {               
     String property = (String)(e.nextElement());    

     if(property.startsWith(FORM_REQUIRED)) 
     {           
     String fieldValue = getProperty(property); 
     String fieldName = property.substring(FORM_REQUIRED.length()); 

     // If the field starts with a ~, then copy the field. 
     //             
     if(fieldValue.startsWith("~"))     
     {              
      String copyProp = fieldValue.substring(1, fieldValue.length()); 
      copyProp = getProperty(copyProp);        

      // Since the parameters have been copied into the form, we can 
      // eke out the duplicate values.         
      //                
      fieldValue = form.getParameterValue(copyProp);     
     }                 

     showSet(fieldName, fieldValue); 
     form.setParameter(fieldName, fieldValue); 
     }            
    }            
    }             

    private void showSet(String fieldName, String fieldValue) 
    {               
    System.out.print("<p class='setting'>");    
    System.out.print(fieldName);       
    System.out.print(" = ");        
    System.out.print(fieldValue);       
    System.out.println("</p>");        
    }               

    private WebForm getWebForm(WebResponse response) 
    throws Exception         
    {             
    WebForm[] forms = response.getForms();   
    String action = getProperty(FORM_ACTION);  

    // Not supposed to break out of a for-loop, but it makes the code easy ... 
    //                   
    for(int i = forms.length - 1; i >= 0; i--)        
     if(forms[ i ].getAction().equalsIgnoreCase(action))     
     return forms[ i ];              

    // Sadly, no form was found. 
    //       
    throw new Exception();  
    }        

    private GetMethodWebRequest getGetMethodWebRequest() 
    { 
    return new GetMethodWebRequest(getProperty(FORM_URL)); 
    } 

    private WebConversation getWebConversation() 
    { 
    if(this.webConversation == null) 
     this.webConversation = new WebConversation(); 

    return this.webConversation; 
    } 

    public void setField(String field, String value) 
    { 
    Hashtable fields = getFields(); 
    fields.put(field, value); 
    } 

    private String getField(String field) 
    { 
    Hashtable<String, String> fields = getFields(); 
    String result = fields.get(field); 

    return result == null ? "" : result; 
    } 

    private Hashtable getFields() 
    { 
    return this.fields; 
    } 

    public static void main(String args[]) 
    throws Exception 
    { 
    FormElements formElements = new FormElements(); 

    formElements.setField("first_name", args[1]); 
    formElements.setField("last_name", args[2]); 
    formElements.setField("email", args[3]); 
    formElements.setField("comments", args[4]); 

    FileInputStream fis = new FileInputStream(args[0]); 
    formElements.load(fis); 
    fis.close(); 

    formElements.run(); 
    } 
} 

一个例子属性文件看起来像:

$ cat com.mellon.properties 

form.url=https://www.mellon.com/contact/index.cfm 
form.action=index.cfm 
form.param.first_name=name 
form.param.last_name= 
form.param.email=emailhome 
form.param.comments=comments 

# Submit Button 
#form.submit=submit 

# Required Fields 
# 
form.required.to=zzwebmaster 
form.required.phone=555-555-1212 
form.required.besttime=5 to 7pm 

来看,它类似于以下(替代路径HttpUnit的和FormElements类$ CLASSPATH):

java -cp $CLASSPATH FormElements com.mellon.properties "John" "Doe" "[email protected]" "To whom it may concern ..." 

合法性

Another answe r提到它可能违反使用条款。首先检查一下,然后再花时间研究技术解决方案。非常好的建议。

+0

哇,谢谢你。时间阅读:D – kgrad 2009-07-17 04:13:57

2

大多数情况下,您可以发送简单的HTTP POST请求。

我建议你试着玩Fiddler来了解网络的工作原理。

几乎所有的编程语言和框架都有发送原始请求的方法。

而且您可以随时针对Internet Explorer ActiveX控件进行编程。我相信很多编程语言都支持它。

1

嗯,这里是从谷歌页面的HTML:

<form action="/search" name=f><table cellpadding=0 cellspacing=0><tr valign=top> 
<td width=25%>&nbsp;</td><td align=center nowrap> 
<input name=hl type=hidden value=en> 
<input type=hidden name=ie value="ISO-8859-1"> 
<input autocomplete="off" maxlength=2048 name=q size=55 title="Google Search" value=""> 
<br> 
<input name=btnG type=submit value="Google Search"> 
<input name=btnI type=submit value="I'm Feeling Lucky"> 
</td><td nowrap width=25% align=left> 
<font size=-2>&nbsp;&nbsp;<a href=/advanced_search?hl=en> 
Advanced Search</a><br>&nbsp;&nbsp; 
<a href=/preferences?hl=en>Preferences</a><br>&nbsp;&nbsp; 
<a href=/language_tools?hl=en>Language Tools</a></font></td></tr></table> 
</form> 

如果你知道如何使您最喜爱的编程语言中的HTTP请求,只要给它一个尝试,看看你会得到什么。试试这个,例如:

http://www.google.com/search?hl=en&q=Stack+Overflow 
0

如果您下载Cygwin,并将Cygwin \ bin添加到您的路径中,则可以使用curl来检索页面和grep/sed/whatever来解析结果。为什么填写表格时,谷歌可以使用querystring参数,反正?使用curl,您也可以发布信息,设置标题信息等。我使用它从命令行调用Web服务。

相关问题