2012-07-20 87 views
0

如何提取使用圖像標記中的樣式屬性給出的背景圖像 在上面的標記中,我想提取圖像。style屬性而不是從SRC我想提取的圖像而不是圖片的路徑從img style =「background:url('path')中提取圖像但不是從src

+0

「我想提取的圖像但不是圖像的路徑「,你是指圖像,圖像本身是什麼? – 2012-07-20 09:19:20

+0

你想要自己的形象嗎? – 2012-07-20 10:01:05

+0

即使我提供從後臺網址提取的完整路徑,圖像也不會顯示。 – Maddy 2012-07-20 10:17:18

回答

0

試試這個

var imageUrl = document.getElementById('myImage').style.background.image.url; 
+0

謝謝您的回覆。一旦所有圖像被提取到imageUrl變量中,我都沒有得到如何使用imageUrl。在上面的答案中,Duane說我們可以在htmlagilitypack中使用HtmlNode,但是我在將圖像放置在帶有文本的輸出文件中時遇到了問題。 – Maddy 2012-07-20 10:01:26

+1

我相信他需要C#代碼,而不是Javascript – 2012-07-20 10:02:22

0

您可以使用HTML Agility pack和:

var images = doc.DocumentNode.Descendants("img").Where(d => d.Attributes.Contains("style") && d.Attributes["style"].Value.Contains("background:url")).ToList(); 

這將返回一個包含所有圖像的類型HtmlAgilityPack<HtmlNode>的列表,然後您可以枚舉它們以獲取值。

+0

謝謝你的回覆。如何在HtmlNode中顯示圖像。我如何在輸出字符串中包含這些圖像。我從網頁中提取圖像和文本。 – Maddy 2012-07-20 09:26:59

+0

我想你可以使用'string.Substring'並得到'background:url'第一次出現的索引,然後讀取所有文本,直到結尾''' – dtsg 2012-07-20 10:04:38

+0

你能告訴我一個示例代碼如何用這個。 以下是我迄今爲止用於提取內容的代碼。 HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); document.LoadHtml(html); var images = document.DocumentNode.Descendants(「img」)。其中(d => d.Attributes.Contains(「style」)&& d.Attributes [ 「風格」] Value.Contains( 「背景:URL」))ToList(); string target =「」; HtmlNodeCollection col = document。DocumentNode.SelectNodes( 「//表[@id = \」 resultsTable \ 「]」); foreach(HtmlNode link in col) { target + = link.InnerHtml; } – Maddy 2012-07-20 10:19:07

0

如果你正在做任何複雜的HTML解析HTML Agility Pack是一個很好的解決方案。

但是,如果這是你想要做的一切,一個簡單的正則表達式就可以做到這一點。

如果您使用css標記,圖像或背景圖像設置圖像,則可以搜索url並提取完整路徑。

這非常簡單的正則表達式將做到這一點。

url\(.*?\) 

從完整路徑中提取圖像路徑應該是微不足道的。

-1

,你也可以使用簡單的正則表達式這個問題xpathing使用HTML敏捷性包

style=background:url\('(?<bgpath>.*)'\) 

在這裏用自己的方式後是一個示例代碼

static void Main(string[] args) 
{ 
    string innerHTML = "<img style=\"background:url('images/logo.jpg')\" />"; 

    string regex = @"style=""background:url\('(?<bgpath>.*)'\)\"""; 
    RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase); 
    Regex reg = new Regex(regex, options); 
    if (reg.IsMatch(innerHTML)) 
    { 
     Console.WriteLine(reg.Match(innerHTML).Groups["bgpath"].Value); 
    } 

    Console.ReadLine(); 
}