Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
84 个问题
嗨, 我正在尝试从网站获取元数据信息。 我正在使用此代码 ,但它给出了一个空值或空值。 这是我的代码:
using HtmlAgilityPack;
using System;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetMetaDataFromUrl(textBox1.Text);
MetaInformation info = new MetaInformation(textBox1.Text);
label1.Text = info.Title;
label2.Text = info.Description;
label3.Text = info.SiteName;
var request = WebRequest.Create(info.ImageUrl);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
}
public static MetaInformation GetMetaDataFromUrl(string url)
{
// Get the URL specified
var webGet = new HtmlWeb();
var document = webGet.Load(url);
var metaTags = document.DocumentNode.SelectNodes("//meta");
MetaInformation metaInfo = new MetaInformation(url);
if (metaTags != null)
{
int matchCount = 0;
foreach (var tag in metaTags)
{
var tagName = tag.Attributes["name"];
var tagContent = tag.Attributes["content"];
var tagProperty = tag.Attributes["property"];
if (tagName != null && tagContent != null)
{
switch (tagName.Value.ToLower())
{
case "title":
metaInfo.Title = tagContent.Value;
matchCount++;
break;
case "description":
metaInfo.Description = tagContent.Value;
matchCount++;
break;
case "twitter:title":
metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
matchCount++;
break;
case "twitter:description":
metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
matchCount++;
break;
case "keywords":
metaInfo.Keywords = tagContent.Value;
matchCount++;
break;
case "twitter:image":
metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
matchCount++;
break;
}
}
else if (tagProperty != null && tagContent != null)
{
switch (tagProperty.Value.ToLower())
{
case "og:title":
metaInfo.Title = string.IsNullOrEmpty(metaInfo.Title) ? tagContent.Value : metaInfo.Title;
matchCount++;
break;
case "og:description":
metaInfo.Description = string.IsNullOrEmpty(metaInfo.Description) ? tagContent.Value : metaInfo.Description;
matchCount++;
break;
case "og:image":
metaInfo.ImageUrl = string.IsNullOrEmpty(metaInfo.ImageUrl) ? tagContent.Value : metaInfo.ImageUrl;
matchCount++;
break;
}
}
}
metaInfo.HasData = matchCount > 0;
}
return metaInfo;
}
}
}
我怎样才能使这个代码工作?
Note:此问题总结整理于: Empty Data in HtmlAgilityPack
尝试替换
GetMetaDataFromUrl(textBox1.Text);
MetaInformation info = new MetaInformation(textBox1.Text);
跟
MetaInformation info = GetMetaDataFromUrl(textBox1.Text);
如果回复有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。