【问题标题】:Cannot read properties of null (reading 'querySelector') at xhr.onload web scraping无法在 xhr.onload 网页抓取中读取 null 的属性(读取“querySelector”)
【发布时间】:2022-06-22 22:12:39
【问题描述】:

script.js

document.addEventListener("DOMContentLoaded", function(){
const $prod = document.getElementById("prod");
const $precio = document.getElementById("precio");

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://cors-anywhere.herokuapp.com/url", true);
xhr.responseType = "document";

xhr.onload = function(){
    /*if(xhr.readyState === 4 && xhr.status === 200){*/
        let response = xhr.responseXML.querySelector(".className");
        console.log(response);
    /*}*/
};

xhr.onerror = function(){
    console.error(xhr.status, xhr.statusText);
}

xhr.send();


}) 

我正在尝试对网页进行网页抓取,但在运行代码时,它会在 xhr.onload 处引发错误无法读取 null 属性(正在读取 'querySelector')。我检查了我是否正确放置了选择器,但显然错误不会出现。 如果有人可以帮助我,我将不胜感激。

【问题讨论】:

  • 为什么readyStatestatus 检查被注释掉了?
  • @Cerbrus — 由于 load 事件仅在请求成功时在状态 4 中触发,所以更好的问题是为什么它首先存在。
  • @Quentin:可能是从教程中复制过来的?

标签: javascript web-scraping xmlhttprequest


【解决方案1】:

错误消息显示xhr.responseXMLnull。选择器无关紧要,没有那么远。

来自MDN

XMLHttpRequest.responseXML只读

返回包含对请求的响应的 Document,如果请求不成功、尚未发送或无法解析为 XML 或 HTML,则返回 null

由于加载事件触发,请求应该既发送又成功,所以解析有问题。

查看浏览器开发者工具的“网络”选项卡中的响应以开始调试。

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2022-08-14
    • 2016-01-14
    • 2021-07-27
    相关资源
    最近更新 更多