【发布时间】:2011-03-23 04:53:33
【问题描述】:
我想从 URL 中获取网站标题和图片。
就像 facebook.com 一样。如何从第三方链接获取图片和网站标题?
【问题讨论】:
标签: c# jquery asp.net jquery-plugins
我想从 URL 中获取网站标题和图片。
就像 facebook.com 一样。如何从第三方链接获取图片和网站标题?
【问题讨论】:
标签: c# jquery asp.net jquery-plugins
使用html Agility Pack这是获取标题的示例代码:
using System;
using HtmlAgilityPack;
protected void Page_Load(object sender, EventArgs e)
{
string url = @"http://www.veranomovistar.com.pe/";
System.Net.WebClient wc = new System.Net.WebClient();
HtmlDocument doc = new HtmlDocument();
doc.Load(wc.OpenRead(url));
var metaTags = doc.DocumentNode.SelectNodes("//title");
if (metaTags != null)
{
string title = metaTags[0].InnerText;
}
}
如有疑问,请发表您的评论。
【讨论】:
在高层次上,您只需将标准 HTTP 请求发送到所需的 URL。这将为您提供网站的标记。然后,您可以检查标记(通过将其解析为 DOM 对象然后查询 DOM,或者通过运行一些简单的正则表达式/模式匹配来查找您感兴趣的内容)以提取诸如文档的 <title> 元素和页面上的任何 <img> 元素。
【讨论】:
在我的脑海中,我会使用 HttpWebRequest 来获取页面并自己解析标题,然后使用进一步的 HttpWebRequests 来获取页面上引用的任何图像。尽管有更好的方法可以做到这一点,但这是一个非常好的机会,并且有人会过来告诉你它是什么。如果不是,它看起来像这样:
HttpWebResponse response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(<your URL here>);
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
//use the StreamReader object to get the page data and parse out the title as well as
//getting locations of any images you need to get
catch
{
//handle exceptions
}
finally
{
if(response != null)
{
response.Close();
}
}
这可能是愚蠢的做法,但这是我的 0.02 美元。
【讨论】:
只是你必须在源正文上使用 javascript 编写
例如
如果你使用母版页只是你必须在 matser 页面上编写代码,这会反映在所有页面上 你也可以像这样在这个脚本中使用图片的 Url 属性
汗莫哈末法赞
【讨论】: