简体   繁体   English

jQuery选择器无法间歇工作

[英]JQuery selector not working intermittently

I am writing a crawler which goes through pages if it detects a ">" type button on current page. 我正在编写一个搜寻器,如果它在当前页面上检测到“>”类型按钮,则可以浏览各个页面。 Code fails about 1 time out of 100 with error "Uncaught TypeError: Cannot read property 'innerText' of undefined". 代码失败100次,失败1次,并显示错误“未捕获的TypeError:无法读取未定义的属性'innerText'”。 In attempt to troubleshoot I open Chrome's developer console and test the selector on that specific page manually. 为了解决问题,我打开了Chrome的开发者控制台,并手动测试了该特定页面上的选择器。 It always returns what I expect and the button is visually there. 它总是返回我所期望的并且按钮在视觉上在那里。 I am puzzled why it fails only rarely and at the same time page where it fails looks normal. 我感到困惑的是,为什么它很少会失败,同时它失败的页面看起来很正常。 Any suggestions how to isolate the problem? 有什么建议如何解决问题?

Code: 码:

lastButton = $(".button a").last()[0];
if(lastButton.innerText === ">") {
    next(lastButton.href, "getFriends", id);
}

At what point does your crawler run that selector? 抓取工具在什么时候运行该选择器? If the page isn't completely finished rendering yet, because the DOM isn't ready, or the code on the page maybe hasn't finished building out the page, your call to $(".button a").last() would return an empty array. 如果页面尚未完全完成渲染(由于DOM尚未准备好),或者页面上的代码可能尚未完成页面的构建,请调用$(".button a").last()将返回一个空数组。 Since you can access any index off that empty array still, when you try to grab the first item out of it you'll get undefined , which would then result in an error when you try to call .innerText off of it. 由于您仍然可以访问该空数组中的任何索引,因此当您尝试从中取出第一个项目时,您将得到undefined ,这将在尝试从中调用.innerText时导致错误。

Try logging how many items are being returned by the selector to see if that is the case. 尝试记录选择器返回的项目数,以查看是否是这种情况。

Found that code in question actually works fine 100% of time. 发现有问题的代码实际上可以在100%的时间内正常工作。 The problem is somehow related to my crawler executing a different scrape function without loading the page for that function. 问题与我的搜寻器执行其他抓取功能而不加载该功能的页面有关。 So the peculiar intermittent problem is somewhere else. 因此,特殊的间歇性问题在其他地方。 Thank you for all who tried to help! 感谢所有尝试提供帮助的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM