特定网站爬取失败:如何激活pastweek类获取alertDetails?
爬取oref.org.il过去一周告警数据的解决方案
你遇到的问题是网站默认展示的不是“过去一周”的告警内容,直接解析页面只能拿到当前展示的数据,要获取pastweek类下的alertDetails,分两种情况处理:
情况1:页面DOM中已包含隐藏的过去一周数据
有些网站会把切换内容提前渲染在DOM里,只是用CSS隐藏。你可以直接修改选择器,定位到pastweek容器下的alertDetails:
修改代码中的选择器部分:
$('.pastweek .alertDetails').each(function() { const alert = $(this).text().trim() alerts.push({ alert }) })
先通过console.log($('.pastweek').html())确认该容器下是否有内容,如果能输出HTML结构,说明这种方法可行。
情况2:需通过AJAX请求获取过去一周数据
如果DOM中没有pastweek的内容,说明点击“In the past week”按钮时,前端会发送AJAX请求加载数据。你可以通过浏览器开发者工具抓包,找到对应的API接口,直接请求接口获取数据:
修改后的完整代码
const PORT = 8000 const axios = require('axios') const cheerio = require('cheerio') const express = require('express') const app = express() // 构造过去一周的日期范围(格式:DD/MM/YYYY) const getDateRange = () => { const toDate = new Date() const fromDate = new Date(toDate.getTime() - 7 * 24 * 60 * 60 * 1000) const format = date => `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}` return { from: format(fromDate), to: format(toDate) } } const { from, to } = getDateRange() // 直接请求历史告警API const apiUrl = `https://www.oref.org.il/WarningMessages/alert/alertsHistory.aspx?lang=en&fromDate=${from}&toDate=${to}` axios.get(apiUrl, { headers: { 'Referer': 'https://www.oref.org.il/12481-en/Pakar.aspx', 'X-Requested-With': 'XMLHttpRequest' } }) .then(response => { const html = response.data const $ = cheerio.load(html) const alerts = [] $('.alertDetails').each(function() { const alert = $(this).text().trim() alerts.push({ alert }) }) console.log(alerts) }) .catch(err => console.log(err)) app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))
说明
网站的历史告警数据是通过AJAX接口加载的,请求时需要带上Referer和X-Requested-With头模拟前端请求,直接调用这个API就能拿到过去一周的所有alertDetails,比解析页面更高效可靠。
内容的提问来源于stack exchange,提问作者Hai Elimelech
相关产品推荐
相关产品推荐

