python爬取网页表格_python提取网页表格并保存为csv
时间: 2024-04-26 19:20:02 浏览: 47
要提取网页表格并保存为 csv,可以使用 Python 的 requests 和 BeautifulSoup 库。
首先,使用 requests 库获取网页内容:
```python
import requests
url = 'https://example.com/table.html'
response = requests.get(url)
```
接着,使用 BeautifulSoup 库解析 HTML,并找到表格元素。假设表格的 `class` 属性为 `my-table`:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'my-table'})
```
接下来,找到表头和表格数据,并将它们转换为列表:
```python
# 找到表头
headers = []
for th in table.find_all('th'):
headers.append(th.text.strip())
# 找到表格数据
data = []
for tr in table.find_all('tr'):
row = []
for td in tr.find_all('td'):
row.append(td.text.strip())
if row:
data.append(row)
```
最后,使用 csv 库将数据保存为 csv 文件:
```python
import csv
with open('table.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(data)
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
import csv
url = 'https://example.com/table.html'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'my-table'})
# 找到表头
headers = []
for th in table.find_all('th'):
headers.append(th.text.strip())
# 找到表格数据
data = []
for tr in table.find_all('tr'):
row = []
for td in tr.find_all('td'):
row.append(td.text.strip())
if row:
data.append(row)
# 保存为 csv 文件
with open('table.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(data)
```
注意:如果表格中包含特殊字符,例如逗号或引号,可能需要使用 csv 模块的特殊处理方法来避免解析错误。
阅读全文
相关推荐












