2

我正在提取中每个元素的名称和值HTML DOM。对于样式属性,只能提取属性名称而不是值。

我的代码如下:

var elementHandles = await page.QuerySelectorAllAsync("a");
    foreach (var handle in elementHandles)
    {
        var elementStyle = await handle.GetPropertyAsync("style");
        var style = await elementStyle.JsonValueAsync();
        var output = style.ToString();
    }   

这是我的输出:

{{
  "0": "font-family",
  "1": "font-size",
  "2": "line-height",
  "3": "color",
  "4": "text-align"
}}

这是我所期待的:

font-family:Arial, Helvetica, sans-serif; 
font-size: 12px; 
line-height: 16px; 
color: #999999;
text-align: left
4

1 回答 1

3

问题是如何CSSStyleDeclaration序列化。如果这就是 Chromium 决定序列化该对象的方式,那么我们就无能为力了。

但是,我们可以尝试使用EvaluateFunctionAsync.

foreach (var handle in elementHandles)
{
  var style = await page.EvaluateFunctionAsync<Dictionary<string, string>>(
    "e => Object.entries(e.style).filter(i => isNaN(i[0]) && i[1]).map(i => { return { [i[0]] : i[1]}}).reduce((acc, cur) => { return {...acc, ...cur}}, {})", handle);
  var output = style.ToString();
}

我们来看看javascript表达式

e=> //We send the HTML element instead of the style property
  Object.entries(e.style) //We get all the property/value pairs from the CSSStyleDeclaration object
    // We want to exclude number properties (like 0,1,2) and empty values
    .filter(i => isNaN(i[0]) && i[1]) 
    //We turn them into objects
    .map(i => { return { [i[0]] : i[1]}})
    //We merge them into one single object that will be returned to C#
    .reduce((acc, cur) => { return {...acc, ...cur}}, {})
于 2019-11-06T12:40:14.067 回答