我正在嘗試獲取此頁面上 div“Notes et références”中的所有鏈接:
https://fr.wikipedia.org/wiki/Barack_Obama
但似乎我沒有正確的選擇器。我試過這個,但沒有用:
const scrollable_section = '#mw-content-text > div.mw-parser-output > div.reference-cadre'
await page.evaluate(selector => {
const element = document.querySelector(selector);
element.scrollTop = element.offsetHeight;
}, scrollable_section);
有人可以幫助我嗎?
我是 Puppeteer 的新手,所以我可能需要更多的解釋。
uj5u.com熱心網友回復:
僅僅因為元素是可滾動的并不意味著您實際上需要滾動才能獲取資料。它通常僅適用于需要處理滾動的 JS 驅動的動態提要。
在這種情況下,資料是靜態可用的,因此除非您出于其他原因使用 Puppeteer,否則您可以使用更簡單且可能更快的 Axios/Cheerio 組合來完成此操作。
更好的是使用維基百科的 API 而不是抓取資料。如果您進行刮擦,請尊重他們對機器人的限制。
繼續使用 Puppeteer,維基百科具有不嵌套部分的奇怪頁面結構。選擇后#Notes_et_références,您可以彈出到 parent <h2>,然后向前迭代幾個同級節點,直到您到達.reference-cadre元素(我對這種關系進行了硬編碼,但是如果更具前瞻性,您可以使用回圈使其更具動態性是一個目標)。
const puppeteer = require("puppeteer");
let browser;
(async () => {
browser = await puppeteer.launch({headless: true});
const [page] = await browser.pages();
const url = "https://fr.wikipedia.org/wiki/Barack_Obama";
await page.goto(url);
const links = await page.evaluate(() =>
[...document.querySelector("#Notes_et_références")
.parentNode
.nextElementSibling
.nextElementSibling
.querySelectorAll("a")]
.map(e => e.getAttribute("href"))
);
console.log(links.length, links.slice(0, 5));
})()
.catch(err => console.error(err))
.finally(() => browser?.close())
;
輸出:
809 [
'#cite_ref-prononciation_1-0',
'#cite_ref-prononciation_1-1',
'/wiki/Prononciation_de_l'anglais',
'/wiki/Anglais_américain',
'/wiki/Transcription_phonétique'
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377789.html
標籤:javascript 节点.js 网页抓取 滚动 傀儡师
