无法在 xhr.onload 网页抓取中读取 null 的属性(读取"查询选择器")



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();

}) 

我正在尝试对网页进行web抓取,但在运行代码时,它在xhr.onload上抛出错误Cannot read properties of null(reading'querySelector')。我已经检查了是否正确放置了选择器,但显然不会出现错误。如果有人能帮我,我将不胜感激。

错误消息表明xhr.responseXMLnull。选择器无关紧要,它不会走那么远。

来自MDN:

XMLHttpRequest.responseXML只读

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

由于加载事件被触发,请求应该被发送并成功,因此解析它时出现了问题。

查看浏览器开发人员工具的"网络"选项卡中的响应,开始对此进行调试。

最新更新