我试图在JavaScript中刮一个网页,其内容如下:

显示的代码是一个更大的循环的一部分,该循环遍历每个repo并擦拭其内容。我已经确认我能够捕获页面上每个回购项目的第一个元素(所以“33-js-概念”的javascript、“操场”的反应、“react google-静态”的反应等等)并能在第一次回购(所以javascript,概念,nodejs,react,角等)中的所有项目。但是在后续循环中继续得到这个错误。这是我的代码:
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: [ [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'
},发布于 2021-03-25 20:54:34
如果你现在只需要这些信息,而这并不是一个大型网站的一部分,你可以这样做:
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);
} 然后,当它失败时,您可以检查主题结构并查看它的失败位置,这样您就可以增强循环来处理特定的情况。如果您可以提供您正在运行的站点或主题的内容,我可以做一个工作示例,无论是在继承时还是失败时。
如果您决定与我们分享这一信息,请不要张贴在这个问题上。使用pastebin.com之类的。
发布于 2021-03-20 03:47:28
这个$('.topics-row-container > a', parent);很像没有返回所有这些元素的数组,在执行for/in时,这些元素会导致对象的循环,而不是数组的循环。
您需要一种方法来返回所有这些'.topics-row-container > a'元素的数组。
你可以用document.querySelectorAll(),
所以,严格地说,这条线:
var topics = $('.topics-row-container > a', parent);可能看起来像:
var topics = parent.querySelectorAll('.topics-row-container > a');发布于 2021-03-20 03:53:35
基本示例,为标记为javascript的存储库获取Github。
fetch('https://api.github.com/search/repositories?q=javascript')
.then(v => v.json()).then((v) => {
console.log(v)
}
)
https://stackoverflow.com/questions/66717912
复制相似问题