【发布时间】: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')。我检查了我是否正确放置了选择器,但显然错误不会出现。 如果有人可以帮助我,我将不胜感激。
【问题讨论】:
-
为什么
readyState和status检查被注释掉了? -
@Cerbrus — 由于 load 事件仅在请求成功时在状态 4 中触发,所以更好的问题是为什么它首先存在。
-
@Quentin:可能是从教程中复制过来的?
标签: javascript web-scraping xmlhttprequest