我可以通过WebClient读取iframe(我想要外部的html)
本文关键字:外部 html 我想要 可以通过 WebClient 读取 iframe | 更新日期: 2023-09-27 17:54:52
我的程序正在读取一个web目标,在body的某个地方有我想要读取的iframe
我的html源代码
<html>
...
<iframe src="http://www.mysite.com" ></iframe>
...
</html>
在我的程序中,我有一个方法将源作为字符串
返回public static string get_url_source(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadString(url);
}
}
我的问题是,我想得到的iframe的源时,它正在读取源,因为它会在正常浏览。
我只能通过使用WebBrowser类或者有一种方法可以在WebClient甚至另一个类中做到这一点吗?
真正的问题:我怎么能得到一个url外部html ?
获得站点的源代码后,您可以使用htmllagilitypack获取iframe的url
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var src = doc.DocumentNode.SelectSingleNode("//iframe")
.Attributes["src"].Value;
然后再次呼叫get_url_source
使用HTML Agility Pack解析源代码,然后:
List<String> iframeSource = new List<String>();
HtmlDocument doc = new HtmlDocument();
doc.Load(url);
foreach (HtmlNode node in doc.DocumentElement.SelectNodes("//iframe"))
iframeSource.Add(get_url_source(mainiFrame.Attributes["src"]));
如果你的目标是一个单一的iframe,尝试使用ID属性或其他东西来识别它,这样你只能检索一个源:
String iframeSource;
HtmlDocument doc = new HtmlDocument();
doc.Load(url);
foreach (HtmlNode node in doc.DocumentElement.SelectNodes("//iframe"))
{
// Just an example for check, but you could use different approaches...
if (node.Attributes["id"].Value == 'targetframe')
iframeSource = get_url_source(node.Attributes["src"].Value);
}
经过一番搜索,我找到了答案,这就是我想要的
webBrowser1.Url = new Uri("http://www.mysite.com/");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
string InnerSource = webBrowser1.Document.Body.InnerHtml;
//You can use here OuterHtml too.