Puppeteer-如何根据内部文本选择元素



我正在用Puppeter抓取一堆页面。内容没有用classes/ids/等进行区分。并且在页面之间以不同的顺序呈现。因此,我需要根据它们的内部文本来选择元素。我在下面包含了一个简化的示例html:

<table>
<tr>
<th>Product name</th>
<td>Shakeweight</td>
</tr>
<tr>
<th>Product category</th>
<td>Exercise equipment</td>
</tr>
<tr>
<th>Manufacturer name</th>
<td>The Shakeweight Company</td>
</tr>
<tr>
<th>Manufacturer address</th>
<td>
<table>
<tr><td>123 Fake Street</td></tr>
<tr><td>Springfield, MO</td></tr>
</table>
</td>
</tr>

在这个例子中,我需要抓取制造商名称和制造商地址。因此,我想我需要根据嵌套th的内部文本选择合适的tr,并在同一tr中刮取相关的td。请注意,该表的行顺序并不总是相同的,并且该表包含的行比这个简化示例多得多,所以我不能只选择第3个和第4个td。

我尝试使用XPATH根据内部文本选择一个元素,如下所示,但似乎不起作用:

var manufacturerName = document.evaluate("//th[text()='Manufacturer name']", document, null, XPathResult.ANY_TYPE, null)

这甚至不是我需要的数据(它将是与这个th相关的td(,但我认为这至少是步骤1。如果有人能提供关于策略的输入,通过内部文本进行选择,或者选择与此th相关的td,我将非常感激

这实际上是一个xpath问题,并不是木偶师特有的,所以这个问题可能也有帮助,因为你需要找到在你找到的<th>之后的<td>:xpath::获取以下Sibling

但是你的xpath对我来说是有效的。在Chrome DevTools中,在你的问题中有HTML的页面上,运行此行来查询文档:

$x('//th[text()="Manufacturer name"]')

注意:$x()是一个仅在Chrome DevTools中工作的辅助函数,尽管Puppeter也有类似的Page.$x函数。

该表达式应该返回一个包含一个元素的数组,即查询中包含该文本的<th>。要获得旁边的<td>

$x('//th[text()="Manufacturer name"]/following-sibling::td')

并获取其内部文本:

$x('//th[text()="Manufacturer name"]/following-sibling::td')[0].innerText

一旦你能够遵循这种模式,你就应该能够使用类似的策略来获得你想要的木偶师数据,类似于这样:

const puppeteer = require('puppeteer');
const main = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://127.0.0.1:8080/');  // <-- EDIT THIS
const mfg = await page.$x('//th[text()="Manufacturer name"]/following-sibling::td');
const prop = await mfg[0].getProperty('innerText');
const text = await prop.jsonValue();
console.log(text);
await browser.close();
}
main();

根据上面答案中的用例解释,以下是用例的逻辑:

await page.goto(url, { waitUntil: 'networkidle2' }); // Go to webpage url
await page.waitFor('table'); //waitFor an element that contains the text
const textDataArr = await page.evaluate(() => {
const trArr = Array.from(document.querySelectorAll('table tbody tr'));
//Find an index of a tr row where th innerText equals 'Manufacturer name'
let fetchValueRowIndex = trArr.findIndex((v, i) => {
const element = document.querySelector('table tbody tr:nth-child(i+1) th');
return element.innerText === 'Manufacturer name';
});
//If the findex is found return the innerText of td of the same row else returns undefined
return (fetchValueRowIndex > -1) ? document.querySelector(`table tbody tr:nth-child(${fetchValueRowIndex}+1) td`).innerText : undefined;
});
console.log(textDataArr);

您可以这样做来获取数据:

await page.goto(url, { waitUntil: 'networkidle2' }); // Go to webpage url
await page.waitFor('table'); //waitFor an element that contains the text
const textDataArr = await page.evaluate(() => {
const element = document.querySelector('table tbody tr:nth-child(3) td'); // select thrid row td element like so
return element && element.innerText; // will return text and undefined if the element is not found
});
console.log(textDataArr);

一次获得所有这些的简单方法:

let data = await page.evaluate(() => {
return [...document.querySelectorAll('tr')].reduce((acc, tr, i) => {
let cells = [...tr.querySelectorAll('th,td')].map(el => el.innerText)
acc[cells[0]] = cells[1]
return acc
}, {})
})

最新更新