我在配置我正在为我目前正在进行的项目工作的网络刮刀时遇到了麻烦
我正在尝试从页面中删除一系列链接,以便评估我要处理的链接。这是我的代码:
public partial class Form1 : Form
{
private byte[] aRequestHTML;
private string sourceString = null;
string[] a;
WebClient objWebClient = new WebClient();
LinkScraper linkScraper = new LinkScraper();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ScrapeLinks(textBox1.Text);
}
public void ScrapeLinks(string sourceLink)
{
// gets the HTML from the url written in the textbox
aRequestHTML = objWebClient.DownloadData(sourceLink);
// creates UTf8 encoding object
UTF8Encoding utf8 = new UTF8Encoding();
// gets the UTF8 encoding of all the html we got in aRequestHTML
sourceString = utf8.GetString(aRequestHTML);
// this is a regular expression to check for the urls
Regex r = new Regex("\\<a\\shref\\=(.*)\\>(.*)\\<\\/a\\>");
// get all the matches depending upon the regular expression
MatchCollection mcl = r.Matches(sourceString);
a = new string[mcl.Count];
int i = 0;
foreach (Match ml in mcl)
{
// Add the extracted urls to the array list
a[i] = ml.ToString();
Console.WriteLine(a[i]);
i++;
}
dataGridView1.DataSource = a;
// binds the databind
// The following lines of code writes the extracted Urls to the file named test.txt
StreamWriter sw = new StreamWriter("test.txt");
foreach (string aElement in a)
{
sw.Write(aElement + "\n");
}
sw.Close();
}
}
我的问题来自于设置我的datagrid数据源。而不是使用字符串列表填充数据网格,而是填充每个字符串长度。正如您将看到我写了一个test.txt文件,看看我是否做了一些愚蠢的事情,但文本文件包含了我希望在数据网格中看到的每个字符串
我已经在论坛上搜索了12个小时的解决方案,但没有任何乐趣
有人可以善意地告诉为什么.Value没有将我的字符串返回到字符串数组'a'以绑定到datagrid吗?
任何帮助总是非常受欢迎
此致 百里
答案 0 :(得分:0)
刚刚找到解决方案的人
DataGridView显示它可以为字符串找到的第一个属性,该字符串是其length属性 解决方法是使用DataTable
DataTable links = new DataTable();
links.Columns.Add("Link URL");
foreach (Match ml in mcl)
{
// Add the extracted urls to table
links.Rows.Add(new object[] {ml.Value});
}
答案 1 :(得分:0)