使用puppeteer.js,我正在尝试自动选择具有给定值的动态列表的元素(page.click)。 在下面的代码中,动态HTML显示3个公司。我要选择一个标有“公司B”的公司。
<div id="ember1222" class="ao-list ember-view">
<div data-test-company-list-row="true" class="list-item" data-ember-action="" data-ember-action-1224="1224">
<a href="#/manage-company/255/dashboard" id="ember1225" class="grid--nested ember-view">
<div data-test-company-name="true" class="grid__cell">
Company A
</div>
</a>
</div>
<div data-test-company-list-row="true" class="list-item" data-ember-action="" data-ember-action-1224="1224">
<a href="#/manage-company/256/dashboard" id="ember1228" class="grid--nested ember-view">
<div data-test-company-name="true" class="grid__cell">
Company B
</div>
</a>
</div>
<div data-test-company-list-row="true" class="list-item" data-ember-action="" data-ember-action-1224="1224">
<a href="#/manage-company/253/dashboard" id="ember1231" class="grid--nested ember-view">
<div data-test-company-name="true" class="grid__cell">
Company C
</div>
</a>
</div>
</div>
我尝试获取元素在数组中的位置:
async selectCompanyName(companyName) {
// Wait for element to be rendered
await page.waitForSelector('[data-test-company-name="true"]', { timeout: settings._30000 });
// Create an array of Company Names
let listCompanyNames = await page.evaluate(() => {
let tds = Array.from(document.querySelectorAll('[data-test-company-name=="true"]'));
return tds.map(td => td.textContent.trim());
});
// Find which row number the Company Name is on and click it
let rowNumber = null;
for (let i = 0; i < listCompanyNames.length; i++) {
if (listCompanyNames[i] === companyName) {
rowNumber = i;
break;
}
}
}
我在数组中找到了正确的位置(即1),但是我不确定我是否知道该如何进行分页。
Ember具有动态ID,因此我坚持使用HTML data-属性。
我尝试了其他方法,例如使用page。$$(),但没有成功。有什么可以帮我吗?
答案 0 :(得分:0)
listCompanyNames
是字符串列表,而不是元素节点,请使用page.$$
返回元素句柄,然后可以使用click()
async selectCompanyName(companyName) {
// Wait for element to be rendered
await page.waitForSelector('[data-test-company-name="true"]', {
timeout: settings._30000
});
let listCompanyNames = await page.$$('[data-test-company-name=="true"]');
for (let i = 0; i < listCompanyNames.length; i++) {
let textContent = await page.evaluate(el => el.textContent, listCompanyNames[i]);
// or
//let textContent = await (await listCompanyNames[0].getProperty('textContent')).jsonValue()
if (textContent === companyName) {
rowNumber = i;
listCompanyNames[i].click()
break;
}
}
}