You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#版Playwright中遍历元素列表并提取子元素信息

如何遍历元素列表并提取元素及其子元素信息?

对应的HTML结构

<div id="parent-content-div">
   <a title="BBC" href="www.bbc.co.uk">
      <div class="category">News</div>
   </a>
   <a title="Google" href="www.google.com">
      <div class="category">Search</div>
   </a>
   <a title="YouTube" href="www.youtube.com">
      <div class="category">Entertainment</div>
   </a>
</div>

已完成的定位与提取代码

已经通过Locator定位到父div内的所有<a>元素:

ILocator Websites = _page.Locator("div[id='parent-content-div']").Locator("a");

当前代码可提取<a>元素的title和href属性:

foreach(var element in Websites.ElementHandlesAsync())
{
    Console.WriteLine(element.GetAttributeAsync("title"));
    Console.WriteLine(element.GetAttributeAsync("href"));
}

子元素文本的正确提取实现

原代码存在异步操作未等待的问题,且获取子元素的方法有误。以下是修正后的完整代码,可同时提取<a>元素属性及子元素.category的文本:

方法一:使用ElementHandle

// 先异步获取所有<a>元素句柄
var websiteElements = await Websites.ElementHandlesAsync();
foreach(var element in websiteElements)
{
    // 等待异步操作完成后获取属性值
    var title = await element.GetAttributeAsync("title");
    var href = await element.GetAttributeAsync("href");
    Console.WriteLine(title);
    Console.WriteLine(href);

    // 定位子元素并获取文本
    var categoryElement = await element.QuerySelectorAsync("div.category");
    if (categoryElement != null)
    {
        var categoryText = await categoryElement.GetTextAsync();
        Console.WriteLine(categoryText);
    }
}

方法二:直接使用Locator(更推荐)

无需转换为ElementHandle,直接通过Locator链式调用定位子元素:

var websites = _page.Locator("div[id='parent-content-div'] a");
// 获取<a>元素总数
int websiteCount = await websites.CountAsync();

for (int i = 0; i < websiteCount; i++)
{
    var currentWebsite = websites.Nth(i);
    // 提取<a>元素属性
    var title = await currentWebsite.GetAttributeAsync("title");
    var href = await currentWebsite.GetAttributeAsync("href");
    // 提取子元素文本
    var categoryText = await currentWebsite.Locator("div.category").TextContentAsync();
    
    Console.WriteLine(title);
    Console.WriteLine(href);
    Console.WriteLine(categoryText);
}

内容的提问来源于stack exchange,提问作者cw84

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:00:54