抓取网页表格数据需根据页面类型选择方法:静态页面可用requests+BeautifulSoup解析HTML,或pandas.read_html直接读取;动态内容则用Selenium模拟浏览器加载,再提取表格并清洗保存为CSV。

抓取网页中的表格数据是Python爬虫常见的任务之一。很多网站以HTML表格(table标签)形式展示结构化信息,比如股票行情、课程表、商品价格等。使用Python可以高效提取这些数据并保存为CSV或Excel格式,便于后续分析。
BeautifulSoup是Python中常用的HTML解析库,适合提取页面中的table、tr、td等标签内容。
基本步骤如下:
import requests
from bs4 import BeautifulSoup
<p>url = '<a href="https://www.php.cn/link/f630930295f2102fb56edc9f88de45fb">https://www.php.cn/link/f630930295f2102fb56edc9f88de45fb</a>'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')</p><p>table = soup.find('table') # 可根据class或id更精确选择
data = []
for row in table.find_all('tr'):
cols = row.find_all(['td', 'th'])
data.append([col.get_text(strip=True) for col in cols])</p><h1>data 现在是一个二维列表,可写入CSV</h1><p>立即学习“Python免费学习笔记(深入)”;
如果网页中的表格结构清晰,pandas的read_html()函数能自动识别并提取所有表格,非常方便。
import pandas as pd <p>url = '<a href="https://www.php.cn/link/85e9b5dce4f9484f6731b0d778f8cc2e">https://www.php.cn/link/85e9b5dce4f9484f6731b0d778f8cc2e</a>' tables = pd.read_html(url) # 返回一个包含所有表格的列表 df = tables[0] # 取第一个表格 print(df.head())
有些网页表格由JavaScript动态生成,requests无法获取完整HTML。这时需要使用Selenium模拟浏览器操作。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
<p>driver = webdriver.Chrome()
driver.get('<a href="https://www.php.cn/link/8edc69aa76b7aac408ba3c248aa8d7d4">https://www.php.cn/link/8edc69aa76b7aac408ba3c248aa8d7d4</a>')
time.sleep(3) # 等待JS加载</p><p>soup = BeautifulSoup(driver.page_source, 'html.parser')
table = soup.find('table')</p><h1>后续提取逻辑同BeautifulSoup</h1><p>driver.quit()
提取后的表格数据常含有多余空格、换行或缺失值,建议进行简单清洗。
import csv
<p>with open('table_data.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
基本上就这些。根据网页情况选择合适的方法,静态页面优先用requests+BeautifulSoup或pandas,动态内容上Selenium。关键在于准确定位表格结构,并稳定提取文本内容。
以上就是Python爬虫怎样抓取表格数据_Python爬虫提取网页中表格数据的实用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号