Python爬虫项目故障:无法抓取Destatis表格数据并生成图表
排查Destatis表格数据抓取失败的解决方案
一、先确保页面完全加载
Selenium常因页面未加载完成就执行抓取导致失败,添加显式等待锁定表格元素:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 最多等待10秒,直到表格出现 wait = WebDriverWait(driver, 10) table = wait.until(EC.presence_of_element_located((By.TAG_NAME, "table")))
二、修正XPath定位逻辑
Destatis表格多为动态生成,直接用固定XPath容易失效,换用列索引定位更可靠:
- 先遍历表头,找到目标列的索引:
headers = table.find_elements(By.TAG_NAME, "th") month_col_idx = None birth_col_idx = None for idx, header in enumerate(headers): if "Monate" in header.text.strip(): month_col_idx = idx if "Geborene Kinder" in header.text.strip(): birth_col_idx = idx
- 根据索引遍历表格行提取数据:
rows = table.find_elements(By.TAG_NAME, "tr") data = [] for row in rows[1:]: # 跳过表头行 cols = row.find_elements(By.TAG_NAME, "td") if len(cols) > max(month_col_idx, birth_col_idx): month = cols[month_col_idx].text.strip() birth = cols[birth_col_idx].text.strip().replace(".", "") # 移除千位分隔符 if month and birth.isdigit(): data.append({"Monate": month, "Geborene Kinder": int(birth)})
三、检查页面特殊结构
- 若表格嵌套在iframe内,需先切换iframe:
iframe = driver.find_element(By.XPATH, "//iframe[contains(@src, 'destatis')]") driver.switch_to.frame(iframe) # 切换后再执行表格定位逻辑
- 若存在Shadow DOM,通过JS脚本获取元素:
shadow_root = driver.execute_script("return document.querySelector('你的阴影宿主元素选择器').shadowRoot") table = shadow_root.find_element(By.TAG_NAME, "table")
四、验证并保存数据
抓取后先打印数据确认有效性,再写入JSON:
import json with open("birth_data.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)
五、图表生成注意事项
读取JSON后处理月份格式,再用matplotlib生成图表:
import matplotlib.pyplot as plt import json with open("birth_data.json", "r", encoding="utf-8") as f: data = json.load(f) months = [item["Monate"] for item in data] births = [item["Geborene Kinder"] for item in data] plt.figure(figsize=(10, 6)) plt.plot(months, births, marker='o') # 折线图,换plt.scatter()可生成散点图 plt.xlabel("Monate") plt.ylabel("Geborene Kinder") plt.title("Geborene Kinder pro Monat") plt.xticks(rotation=45) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者DarkKnight22
相关产品推荐
相关产品推荐

