如何从 StreamReader 创建字符串以进行分析
本文关键字:字符串 StreamReader 创建 | 更新日期: 2023-09-27 18:34:16
我希望能够搜索给定的HTML并找到某些标签
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = "http://www.google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
}
}
如何将我从流阅读器获得的内容转换为字符串,以便我可以进行进一步的分析......
看看 HTML Agility Pack。使用该敏捷包将获得比使用字符串函数自己解析 html 更好的结果。
由于您正在处理 Windows 窗体应用程序,请使用 WebBrowser 控件。由于您可以访问 DOM,因此很容易找到具有此功能的元素。
这是来自控制台应用的代码片段:
这是我通过HttpWebRequest获取强力球主页的代码,并使用正则表达式查找头奖,并读取当前头奖。
希望这对你有帮助。
string url = ConfigurationManager.AppSettings.GetValues("PBHomePage")[0];
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.ContentType = "text/html";
Regex regex = new Regex("(<font size='"6'" color='"#FFFFFF'"><strong>''$)(''d+)(''.*)(''d*)(''s+Million</strong></font>)");
try
{
WebResponse response = webReq.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string webPage = reader.ReadToEnd();
if (!regex.IsMatch(webPage)) { return null; }
GroupCollection groups = regex.Match(webPage).Groups;
StringBuilder strJackpot = new StringBuilder(groups[2].Value);
if (!string.IsNullOrEmpty(groups[3].Value) && !string.IsNullOrEmpty(groups[4].Value))
{
strJackpot.Append(groups[3].Value + groups[4].Value);
}
jackpot = double.Parse(strJackpot.ToString());
}
catch (WebException ex)
{
Console.WriteLine("Error in getting Latest Jackpot");
}