如何在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
相关产品推荐
相关产品推荐

