node-fetch, jako pewnego rodzaju zamiennik przeglądarkowego Fetch API, służy do obsługi zapytań HTTP, a nie DOM-u. Żeby zrobić coś na DOM-ie z pobranej przez fetch strony, najpierw musisz powinieneś jej kod HTML sparsować na DOM przy pomocy np. jsdom lub DOMParser (w przypadku przeglądarki) i dopiero wtedy pobierać z niego co Ci potrzeba przy użyciu np. document.querySelectorAll (tym pobierzesz wszystkie elementy na podstawie konkretnego selektora).
miałem problem z zainstalowaniem jsdom, więc znalazłem i zainstalowałem htmparser2, lecz na ich stronie jest taki przykład użycia:
const htmlparser2 = require("htmlparser2"); const parser = new htmlparser2.Parser({ onopentag(name, attributes) { /* * This fires when a new tag is opened. * * If you don't need an aggregated `attributes` object, * have a look at the `onopentagname` and `onattribute` events. */ if (name === "script" && attributes.type === "text/javascript") { console.log("JS! Hooray!"); } }, ontext(text) { /* * Fires whenever a section of text was processed. * * Note that this can fire at any point within text and you might * have to stich together multiple pieces. */ console.log("-->", text); }, onclosetag(tagname) { /* * Fires when a tag is closed. * * You can rely on this event only firing when you have received an * equivalent opening tag before. Closing tags without corresponding * opening tags will be ignored. */ if (tagname === "script") { console.log("That's it?!"); } }, }); parser.write( "Xyz <script type='text/javascript'>const foo = '<<bar>>';</ script>" ); parser.end();
ale nie do końca rozumiem gdzie wpisuje się kod html. czy wcześniej trzeba utworzyć zmienną name i attributes i tam powpisywać dane? Prosiłbym o odpowiedź
miałem problem z zainstalowaniem jsdom
Jaki problem?
Co do biblioteki htmlparser2, w skład jej ekosystemu wchodzi moduł domhandler i w jego dokumentacji jest przykład parsowania HTML do DOM - natomiast wygląda to na dość niskopoziomową obsługę (choć są metody podobne do DOM-owych); wg mnie jsdom jest prostszy w obsłudze. Możesz też posłużyć się biblioteką Cheerio, która jest implementacją jQuery po stronie serwera, więc i ewentualne procesowanie DOM-u będzie wygodniejsze.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm ERR! code 1 npm ERR! path C:\Users\cichy\Desktop\test\node_modules\contextify npm ERR! command failed npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using node-gyp@7.1.2 npm ERR! gyp info using node@16.8.0 | win32 | x64 npm ERR! gyp info find Python using Python version 3.9.7 found at "C:\Python39\python.exe" npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt npm ERR! gyp ERR! find VS checking VS2019 (16.11.31624.102) found at: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools" npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features" npm ERR! gyp ERR! find VS - missing any VC++ toolset npm ERR! gyp ERR! find VS checking VS2017 (15.9.28307.1622) found at: npm ERR! gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools" npm ERR! gyp ERR! find VS - found "Visual Studio C++ core features" npm ERR! gyp ERR! find VS - found VC++ toolset: v141 npm ERR! gyp ERR! find VS - missing any Windows SDK npm ERR! gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use npm ERR! gyp ERR! find VS looking for Visual Studio 2015 npm ERR! gyp ERR! find VS - not found npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload. npm ERR! gyp ERR! find VS For more information consult the documentation at: npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47) npm ERR! gyp ERR! stack at C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16 npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14) npm ERR! gyp ERR! stack at C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14 npm ERR! gyp ERR! stack at C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16 npm ERR! gyp ERR! stack at C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7 npm ERR! gyp ERR! stack at C:\Users\cichy\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16 npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:404:5) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:394:28) npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1064:16) npm ERR! gyp ERR! System Windows_NT 10.0.19043 npm ERR! gyp ERR! command "D:\\NodeJS\\node.exe" "C:\\Users\\cichy\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" npm ERR! gyp ERR! cwd C:\Users\cichy\Desktop\test\node_modules\contextify npm ERR! gyp ERR! node -v v16.8.0 npm ERR! gyp ERR! node-gyp -v v7.1.2 npm ERR! gyp ERR! not ok npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\cichy\AppData\Local\npm-cache\_logs\2021-09-18T19_25_16_950Z-debug.log
teraz jak spróbowałem to zainstalowało się bez błędów i przeszedłem do "Document.QuerySelectorAll()" lecz napotkałem błąd. Dałem przykładowy kod:
const jsdom = require("jsdom"); const { JSDOM } = jsdom; const dom = new JSDOM(`<p>ssss</p><p>dddd</p>`); console.log(dom.window.document.querySelectorAll("p").textContent);
ale konsola wypisała "undefined" zaś jeśli zamieniłem to na "Document.QuerySelector()" to rzecz jasna wypisało mi tylko "ssss" na czym mi nie zależy.
Pozdrawiam
document.querySelectorAll zwraca listę elementów (w przeciwieństwie do querySelector, który zwraca pierwszy znaleziony element). Więc, żeby odczytać cokolwiek z danego elementu listy, najpierw podaj jego indeks - wygodnie jest użyć do tego pętli.
chyba nie do końca wszystko zrozumiałem, bo zrobiłem taki przykładowy pogram:
const jsdom = require("jsdom"); const { JSDOM } = jsdom; const dom = new JSDOM(`<p>ssss</p><p>dddd</p>`); NodeList = dom.window.document.querySelectorAll("p").textContent; for (let i = 0; i < NodeList.length; i++){ let item = NodeList[i]; console.log(item); }
ale wyskoczył błąd, że nie można odczytać wartości NodeList.lenght albo nieznaleziono. Prosiłbym o ewentualne korekty
Wartość zwrócona z dom.window.document.querySelectorAll("p") nie posiada property textContent, stąd błąd przy próbie odczytu NodeList.length.
Zamiast:
NodeList = dom.window.document.querySelectorAll("p").textContent;
zapisz:
const nodeList = dom.window.document.querySelectorAll("p");
Wtedy w pętli będziesz mógł iterować pod nodeList. Przy okazji: zapisz to z małej litery (jako np. camelCase), bo nie jest to referencja do konstruktora/klasy, a konwencja nazewnicza PascalCase jest używana właśnie dla tego typu wartości.
zmieniłem kod na taki:
const { JSDOM } = jsdom; const dom = new JSDOM(`<p>ssss</p><p>dddd</p>`); const nodeList = dom.window.document.querySelectorAll("p"); for (let i = 0; i < nodeList.length; i++){ let item = nodeList[i]; console.log(item); }
i otrzymałem 2 wartości:
HTMLParagraphElement {}
Teraz sobie w pętli możesz wypisać np. textContent z danego item. Analogicznie jakbyś chciał wypisać propertisy obiektów z tablicy wewnątrz pętli.
querySelector[All] przyjmuje selektor CSS, więc możesz nim pobrać elementy na podstawie id i klasy oraz atrybutów pokroju name, value, data-* itp.
93,733 zapytań
142,669 odpowiedzi
323,287 komentarzy
63,293 pasjonatów
Motyw:
Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡
Oto polecana książka warta uwagi.Pełną listę książek znajdziesz tutaj
Aby uzyskać rabat -10%, użyjcie kodu pasja-linux, wpisując go w specjalne pole w koszyku.