Visual Studio C# 如何与网站进行交互

3
我想制作一个可以与现有网站交互的应用程序。该网站有一些与搜索相关的文本框字段,用户通常在其中输入内容,然后点击按钮进入下一页。我想通过制作一个Visual Studio C# 应用程序来自动化这个过程。我不确定从哪里开始,似乎大多数教程都是针对创建自己的网站而非与现有网站进行交互。
据我所知,输入搜索内容并单击按钮似乎不会创建唯一的URL字符串(不像Google地图那样),因为当它将我带到搜索结果时,URL不会改变。我不确定需要发送什么类型的TCP命令(我知道“GET”,但仅限于此)。
有什么指导吗?

1
看看Selenium。 - Daniel A. White
1
正如Daniel所建议的,这里为您提供一个快速入门:http://scraping.pro/example-of-scraping-with-selenium-webdriver-in-csharp/ - kenny
可能是使用C#与网页交互的重复问题 - Victor Zakharov
看起来最简单的方法就是引用Selenium dll,但我更想了解它的工作原理。看起来源代码是开源的,所以也许我可以挖掘大量的文件并找出答案。 - jerp
1个回答

1
将文本输入到URL中将产生一个GET请求。TCP只是HTTP协议下的底层协议。
你需要的是一个HTTP POST请求。
WebRequest开始。
// Create a request using a URL that can receive a post. 
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
< p > postData 变量包含您想要“插入”到文本框中的元素。这应该为您提供了一个良好的起点。我一直在使用这种技术处理涉及网站交互的所有项目。

Selenium,如评论中所建议的,可能是一个选择,只要您不介意需要安装特定的浏览器,因为它利用它来完成此目的。如果您想部署您的应用程序,则这不是一个好的解决方案。


谢谢!有了这个,再加上一点Wireshark嗅探,我就能实现我的目标了。 - jerp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接