html中的相对路径变成绝对路径-高手指教

leotao841024 2012-09-25 10:01:12
现在做一个网站页面抓取的功能,但是因为网站html的路径都是相对路径,想请教怎么解决这个问题,页面中包含a标签,img标签等,css里也有可能有img这样的相对路径的代码,外部css的引用,外部js的引用都是相对路径,请教,谢谢!
...全文
455 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
leotao841024 2012-09-26
  • 打赏
  • 举报
回复
期待高手
leotao841024 2012-09-26
  • 打赏
  • 举报
回复
期待高手
leotao841024 2012-09-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

private static string ConvertToAbsoluteUrls (string html, Uri relativeLocation) {
IHTMLDocument2 doc = new HTMLDocumentClass ();
doc.write (new object [] { html });
doc.close ();

……
[/Quote]
这个我也找到了,只是引用了mshtml后提示错误
无法嵌入互操作类型“mshtml.HTMLDocumentClass”。请改用适用的接口。
类型“mshtml.HTMLDocumentClass”未定义构造函数
yang_lawrence 2012-09-26
  • 打赏
  • 举报
回复
private static string ConvertToAbsoluteUrls (string html, Uri relativeLocation) {
IHTMLDocument2 doc = new HTMLDocumentClass ();
doc.write (new object [] { html });
doc.close ();

foreach (IHTMLAnchorElement anchor in doc.links) {
IHTMLElement element = (IHTMLElement)anchor;
string href = (string)element.getAttribute ("href", 2);
if (href != null) {
Uri addr = new Uri (relativeLocation, href);
anchor.href = addr.AbsoluteUri;
}
}

foreach (IHTMLImgElement image in doc.images) {
IHTMLElement element = (IHTMLElement)image;
string src = (string)element.getAttribute ("src", 2);
if (src != null) {
Uri addr = new Uri (relativeLocation, src);
image.src = addr.AbsoluteUri;
}
}

string ret = doc.body.innerHTML;

return ret;
}
leotao841024 2012-09-26
  • 打赏
  • 举报
回复
能详细说下嘛我不大理解你这句话的意思
[Quote=引用 1 楼 的回复:]

取网页的url,把文件名和查询部分,替换为相对路径那部分字符串,应该就可以。
[/Quote]
dalmeeme 2012-09-26
  • 打赏
  • 举报
回复
		string cssPath = "css/common.css";
string htmlUrl = @"http://topic.csdn.net/u/20120925/22/953c6420-7b9d-4603-91cc-cd501a9c713f.html?id=3";
string basePath = Path.GetDirectoryName(htmlUrl);
string result = Path.Combine(basePath, cssPath).Replace(@"\", "/");
Response.Write(result);

以上是示例,htmlUrl是网页的url,cssPath是该网页里引用的一个css文件相对路径。
dalmeeme 2012-09-25
  • 打赏
  • 举报
回复
取网页的url,把文件名和查询部分,替换为相对路径那部分字符串,应该就可以。

62,133

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧