gpt4 book ai didi

javascript - JavaScript 中的网页抓取

转载 作者:行者123 更新时间:2023-12-04 13:28:20 24 4
gpt4 key购买 nike

我正在尝试用 JavaScript 抓取一个如下所示的网页:
enter image description here
显示的代码是一个更大循环的一部分,它遍历每个 repo 并抓取它的内容。
我已经确认我能够捕获页面上每个 repo 项的第一个元素(所以“33-js-concepts”的 javascript,“playground”的 react ,“react-google-static”的 react "等)并且可以抓取第一个 repo 中的所有项目(例如 javascript、concept、nodejs、react、angular 等),但在后续循环中不断收到此错误。这是我的代码:

r.topic = []; // topics used in the repo:
var topics = $('.topics-row-container > a', parent);
if(topics && topics.length > 0) {
for (var i in topics) {
r.topic.push(topics[i].children[0].data.replace(/^\s+|\s+$/g, ''));

}
console.log(r.topic);
第一个循环产生预期的结果,使用 console.log(r.topic) 打印:
[
'javascript',
'concepts',
'nodejs',
'react',
'angular',
'programming',
'javascript-programming'
]
但随后的循环会产生以下错误:
r.topic.push(topics[i].children[0].data.replace(/^\s+|\s+$/g, ''));
^
TypeError: Cannot read property '0' of undefined
我是 javascript 新手,所以我想我错过了一些明显的东西,但我不明白为什么 children 会抛出这个错误。我什至尝试这样做,这样 children 每次循环都会增加一,但我仍然看到同样的错误。
我真的很感激任何帮助!
更新:
打印到控制台的主题如下所示:
children: [ [Node] ],
parent: Node {
type: 'tag',
name: 'div',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: [Object: null prototype],
'x-attribsNamespace': [Object: null prototype],
'x-attribsPrefix': [Object: null prototype],
children: [Array],
parent: [Node],
prev: [Node],
next: [Node]
},
prev: Node {
type: 'text',
data: '\n ',
parent: [Node],
prev: [Node],
next: [Circular *7]
},
next: Node {
type: 'text',
data: '\n ',
parent: [Node],
prev: [Circular *7],
next: null
}
},
options: { xml: false, decodeEntities: true },
_root: <ref *8> initialize {
'0': Node {
type: 'root',
name: 'root',
parent: null,
prev: null,
next: null,
children: [Array],
'x-mode': 'no-quirks'
},

最佳答案

如果您现在只需要这些信息,并且这不是经常执行此操作的较大站点的一部分,则您可以:

if (topics[i] && topics[i].children && 
topics[i].children[0] && topics[i].children[0].data)
r.topic.push(topics[i].children[0].data.replace(/^\s+|\s+$/g, ''));
它没有找到一些元素。如果您想真正寻找正在发生的事情以便使其适用于所有情况,您可以:
r.topic = []; // topics used in the repo:
var topics = $('.topics-row-container > a', parent);
try {
if(topics && topics.length > 0) {
for (var i in topics) {
r.topic.push(topics[i].children[0].data.replace(/^\s+|\s+$/g, ''));
}
console.log(r.topic);
}
} catch(error) {
console.log(error, topics);
}
然后,当它失败时,您可以检查主题结构并查看失败的地方,这样您就可以增强循环以处理该特定情况。
如果您可以提供您正在运行它的站点或主题 var 的内容,无论是成功还是失败,我都可以做一个工作示例。
如果您决定与我们分享此信息,请不要将其发布在问题上。使用 pastebin.com或者其他的东西。

关于javascript - JavaScript 中的网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66717912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com