我有一个正在工作的项目,要求我能够将信息输入到网页中,阅读重定向到的下一页,然后采取进一步的措施。一个简化的实际示例就是去google.com,输入“编码技巧”作为搜索条件,然后阅读结果页面。
小型编码示例,例如链接到http://www.csharp-station.com/HowTo/HttpWebFetch.aspx的示例,讲述了如何阅读网页,但没有通过向表单提交信息并继续进行操作来与之交互的方法。转到下一页。
出于记录,我没有在开发恶意和/或垃圾邮件相关产品。
那么,我该如何阅读需要首先进行几步正常浏览的网页?
您可以以编程方式创建Http请求并检索响应:
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
Run Code Online (Sandbox Code Playgroud)
当然,此代码将返回错误,因为Google将GET(而不是POST)用于搜索查询。
如果您要处理特定的网页,则此方法将起作用,因为URL和POST数据基本上都是硬编码的。如果您需要更具动态性的内容,则必须:
FWIW,我认为像Perl或Python之类的东西可能更适合此类任务。
编辑:x-www-form-urlencoded
归档时间: |
|
查看次数: |
6917 次 |
最近记录: |