我在找一条具体的短信。在我的例子中,我不知道目标的HTML代码中有选择器、元素、父母或其他任何东西。只是想找出这个页面是否有robots.txt。通过搜索“用户代理:”来做到这一点。
是否有人知道如何在解析中搜索特定的文本,而不知道页面上的任何其他信息?
getApiTest = async () => {
axios.get('http://webilizerr.com/robots.txt')
.then(res => {
const $ = cheerio.load(res.data)
console.log($(this).text().trim() === 'User-agent:'
)
}).catch(err => console.error(err))
};耽误您时间,实在对不起。
发布于 2022-05-15 16:09:35
您只需使用一个正则表达式来检查“用户代理”是否是返回的HTML的一部分。
注意:如果被刮过的页面没有robots.txt文件并返回一个404状态代码(通常应该是这样),则axios会抛出一个错误。您应该在catch语句中考虑这一点。
以下是一个工作示例:
const axios = require("axios");
const cheerio = require("cheerio");
const getApiTest = async () => {
try {
const res = await axios.get("https://www.finger.digital/robots.txt");
const $ = cheerio.load(res.data);
const userAgentRegExp = new RegExp(/User-agent/g);
const userAgentRegExpResult = userAgentRegExp.exec($.text());
if (!userAgentRegExpResult) {
console.log("Doesn't have robots.txt");
return;
}
console.log("Has robots.txt");
} catch (error) {
console.error(error);
console.log("Doesn't have robots.txt");
}
};
getApiTest();https://stackoverflow.com/questions/72249512
复制相似问题