我有问题,但我不知道如何搜索。
我用c#在Visual Studio上做了一个简单的机器人。当我在文本框中编写链接时,机器人会进入网站并取得标题,然后将其写入另一个文本框中。没关系。
之后,我创建一个mssql数据库。例如,有30条线,30个不同的链接。当我单击按钮时,我希望该漫游器转到每一行中的每个网站,并将其标题保存到数据库中。
我可以那样做吗?
我正在使用Visual Studio
private void simpleButton2_Click(object sender, EventArgs e)
{
verial(txt_kaynak.Text, "//*[@id='cph1_lblKabulTar']", txtbox_tarihyaz);
}
public void verial(string Url, string xpath, TextBox Sonuc)
{
try
{
url = new Uri(Url);
}
catch (UriFormatException)
{
if (MessageBox.Show("hata-1!", "Hata", MessageBoxButtons.OK) == DialogResult.OK)
{
}
}
catch (ArgumentNullException)
{
if (MessageBox.Show("hata-2!", "Hata", MessageBoxButtons.OK) == DialogResult.OK)
{
}
}
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
try
{
html = client.DownloadString(url);
}
catch (WebException)
{
if (MessageBox.Show("hata-3!", "Hata", MessageBoxButtons.OK) == DialogResult.OK)
{
}
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
try
{
// Sonuc.Items.Add(doc.DocumentNode.SelectSingleNode(xpath).InnerText);
txtbox_tarihyaz.Text = doc.DocumentNode.SelectSingleNode(xpath).InnerText;
}
catch (NullReferenceException)
{
if (MessageBox.Show("hatalı xpath!", "Hata", MessageBoxButtons.OK) == DialogResult.OK)
{
}
}
答案 0 :(得分:0)
首先编写代码以获取URL列表。可能看起来像这样:
public IEnumerable<string> GetListOfUrls()
{
using (var conn = new SqlConnection(connectionString)
{
var cmd = new SqlCommand("SELECT Url FROM List", conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
yield return reader.GetString(0);
}
}
}
然后在点击处理程序中调用它并对其进行迭代,为每一行调用您的方法:
private void simpleButton2_Click(object sender, EventArgs e)
{
var list = GetListOfUrls();
foreach (var url in list)
{
verial(url, "//*[@id='cph1_lblKabulTar']", txtbox_tarihyaz);
}
}