【问题标题】:replacing attributes within an html image tag替换 html 图像标签中的属性
【发布时间】:2017-05-04 16:29:53
【问题描述】:

我有 1000 多个包含 html 图像标签的数据库条目。

问题是,90% 的 'src' 属性只是占位符。我需要用适当的真实来源替换所有这些占位符。

典型的数据库条目如下所示(图像标签的数量因条目而异):

<p>A monster rushes at you!</p>
Monster:<p><img id="d8fh4-gfkj3" src="(image_placeholder)" /></p>
<br />
Treasure: <p><img id="x23zo-115a9" src="(image_placeholder)" /></p>
Please select your action below:
</br />

使用上面图像标签中的 ID,“d8fh4-gfkj3”和“x23zo-115a9”,我可以查询另一个函数来获取这些图像的“真实”来源。

所以我尝试使用 HtmlAgilityPack 并想出了这个(下):

    Dim doc As New HtmlDocument()
    doc.LoadHtml(encounterText)

    For Each imgTag As HtmlNode In doc.DocumentNode.SelectNodes("//img")
        'get the ID
        Dim imgId As HtmlAttribute = imgTag.Attributes("id")
        Dim imageId As String = imgId.Value

        'get the new/real path
        Dim newPath = getMediaPath(imageId)
        Dim imgSrc As HtmlAttribute = imgTag.Attributes("src")

        'check to see if the <img> tag "src" attribute has a placeholder
        If imgSrc.Value.Contains("(image_placeholder)") Then
            'replace old image src attribute with 'src=newPath'
        End If
    Next

但我不知道如何用新值实际替换旧值。

有没有办法用 HtmlAgilityPack 做到这一点?

谢谢!

【问题讨论】:

    标签: vb.net html-agility-pack


    【解决方案1】:

    你应该可以只设置属性的值:

    'check to see if the <img> tag "src" attribute has a placeholder
    If imgSrc.Value.Contains("(image_placeholder)") Then
        'replace old image src attribute with 'src=newPath'
        imgSrc.Value = newPath
    End If
    

    替换后,您可以通过以下方式获取更新后的 HTML:

    doc.DocumentNode.OuterHtml
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2019-05-27
      • 2013-05-01
      • 2018-02-20
      • 1970-01-01
      • 2010-11-24
      相关资源
      最近更新 更多