如何使用python爬取网页数据存储到excel表中
时间: 2023-12-29 21:06:07 浏览: 42
要将网页数据存储到 Excel 表中,可以使用 Pandas 库和 openpyxl 库。
首先,使用 Pandas 库将网页数据读入到 DataFrame 中。然后,使用 openpyxl 库将 DataFrame 中的数据写入到 Excel 表中。
下面是一个示例代码:
```python
import pandas as pd
from openpyxl import Workbook
# 发送 HTTP 请求获取网页内容
url = 'https://www.example.com'
response = requests.get(url)
html = response.text
# 将网页内容读入到 DataFrame 中
df = pd.read_html(html)[0]
# 创建 Excel 表
wb = Workbook()
ws = wb.active
# 将 DataFrame 中的数据写入到 Excel 表中
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
# 保存 Excel 表
wb.save('example.xlsx')
```
其中,pd.read_html() 方法可以将 HTML 表格转换成 Pandas DataFrame,dataframe_to_rows() 方法可以将 DataFrame 转换成行列表。将行列表写入到 Excel 表中时,需要使用 ws.append() 方法。最后,使用 wb.save() 方法保存 Excel 表。
需要注意的是,写入 Excel 表时需要安装 openpyxl 库。另外,写入中文时需要设置编码格式,例如:
```python
ws.cell(row=i, column=j, value=str(df.iloc[i-2,j-1]).encode('utf-8'))
```