0

有什么方法可以使用AngleSharp来获取所有身体标签的数量,然后为所有标签分配一个唯一的属性 id,例如“data-id=1”、“data-id=2”等。

我正在为静态网站翻译目的进行测试,然后我将使用查询选择器 [data-id] 并从每个标签中获取 TextContent 并使用翻译 API 翻译文本并将翻译后的文本设置回标签 id where它是从最初提取的。

C#

var html = File.ReadAllText(@"C:\example.html");
    var parser = new HtmlParser();
    var document = parser.Parse(html);

    var elements = document.All.Where(o => o.NodeType == AngleSharp.Dom.NodeType.Text && o.TextContent.Trim() != ""); // If text, assign id.
    if(elements != null)
    {
        int number = 0;
        foreach(var element in elements)
        {
            element.SetAttribute("data-id", number.ToString());
            number++;

            element.OuterHtml.Dump();
        }
    }

HTML

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My page heading</h1>
<h2>This is example static page to get all the HTML tags and their <strong>childrens content </strong> and then <span>translate</span>
that into </br> another language.
</h2>
<p>Something in footer</p>
</body>
</html>
4

1 回答 1

1

看起来像下面这样做。基本上它从 Body 元素中收集所有降序元素,循环它们并添加属性。也许您在遍历所有后代时遇到了麻烦。

我将正文更新后的内部 html 写入文本文件,以便您看到“data-id”属性。

class Program
{
    static void Main(string[] args)
    {

        var response = getHtml("http://www.bbc.com");
        var html = response.Result;

        HtmlParser htmlParser = new HtmlParser();
        var parsedDoc = htmlParser.Parse(html);
        var body = parsedDoc.Body;
        var elements = getAllElements(parsedDoc.Body);

        for(var i = 0; i < elements.Count; i++)
        {
            var child = elements[i];
            child.SetAttribute("data-id", $"data-id{i + 1}");
        }

        File.WriteAllText("E:/soQuestion.txt", parsedDoc.Body.InnerHtml);
    }

    static async Task<string> getHtml(string url)
    {
        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.GetAsync(url);

            //if http request did not succeeed, return empty html
            if (!response.IsSuccessStatusCode) return string.Empty;

            var content = await response.Content.ReadAsStringAsync();
            return content;
        }

    }

    static List<IElement> getAllElements(IElement element)
    {
        List<IElement> elements = new List<IElement>();

        //add element itself
        elements.Add(element);

        foreach (var child in element.Children)
        {
            //add each child elements
            elements.AddRange(getAllElements(child));
        }

        return elements;
    }
}
于 2018-06-26T13:08:49.907 回答