使用Python从网页HTML提取发布日期遇阻,寻求技术协助
解决微软安全博客发布日期提取问题
问题根源
- 页面可能是JavaScript动态渲染:直接用
requests获取的原始HTML未加载动态内容,导致目标元素缺失 - 元素选择器错误:微软博客的日期元素有固定的结构化存储位置,若之前用的class或标签不对,自然提取失败
- 请求头缺失:微软服务器会拦截无合法
User-Agent的请求,返回不完整内容
可行解决方案
方案1:解析Meta标签(无需动态渲染)
微软安全博客的发布日期会放在meta标签的property="article:published_time"属性中,这是最稳定的提取方式:
import requests from bs4 import BeautifulSoup url = "https://www.microsoft.com/en-us/security/blog/2024/01/29/join-us-at-infosec-jupyterthon-2024/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 提取Meta标签中的日期 date_meta = soup.find("meta", property="article:published_time") if date_meta: print("发布日期:", date_meta["content"]) else: print("未找到发布日期")
方案2:修正htmldate模块使用
确保请求头合法,直接传入完整响应内容即可:
import requests import htmldate url = "https://www.microsoft.com/en-us/security/blog/2024/01/29/join-us-at-infosec-jupyterthon-2024/" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) publish_date = htmldate.find_date(response.text) print("发布日期:", publish_date)
方案3:Selenium处理动态渲染(极端情况)
若页面完全依赖JS渲染,用无头浏览器模拟加载后提取:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options url = "https://www.microsoft.com/en-us/security/blog/2024/01/29/join-us-at-infosec-jupyterthon-2024/" # 配置无头Chrome chrome_options = Options() chrome_options.add_argument("--headless=new") driver = webdriver.Chrome(options=chrome_options) driver.get(url) # 等待页面加载完成 driver.implicitly_wait(3) # 提取Meta标签日期 date_element = driver.find_element(By.CSS_SELECTOR, "meta[property='article:published_time']") print("发布日期:", date_element.get_attribute("content")) driver.quit()
核心注意事项
- 所有请求必须添加合法
User-Agent,否则会被服务器拦截 - 优先使用Meta标签提取,这是微软博客页面的结构化数据存储标准,比定位页面元素更可靠
内容的提问来源于stack exchange,提问作者Lopa
相关产品推荐
相关产品推荐

