2013-01-20 121 views
0

那麼我的程序正在讀取一個web目標,在身體的某個地方有我想要讀取的iframe。我可以通過WebClient讀取iframe(我想要外部html)嗎?

我的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 Class來做到這一點,還是有辦法在WebClient或其他課程中做到這一點?

真正的問題: 我怎樣才能得到外部html給定的網址?任何appoach歡迎。

+0

猜你可以通過Java腳本訪問URL ... –

+1

要知道,你可能如果您訪問另一個域的頁面,則會遇到跨站點腳本的安全問題。 –

+0

是的iframe來自另一個域,但爲什麼這是一個問題? – Incognito

回答

0

第二個電話嘛,我發現一些搜索之後的答案,這就是我想要的

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. 
2

使用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); 
} 
+0

是的即時通訊定位單個iframe,虐待你的例子,並會回覆。 – Incognito

3

獲取該網站的源代碼後,您可以使用HtmlAgilityPack獲取iframe的url

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(html); 

var src = doc.DocumentNode.SelectSingleNode("//iframe") 
      .Attributes["src"].Value; 

然後對get_url_source

+0

這會導致iframe更改其數據。 – Incognito

+0

@Incognito,「更改其數據」?這是什麼意思?怎麼樣? – I4V

+0

,因爲它的時間iframe加載新數據生成,所以我想第一次生成的數據,我加載頁面。就像有一個腳本,它在iframe中生成隨機數字。 – Incognito

相關問題