原有data数据添加python爬取的一列数据
时间: 2023-09-19 22:09:13 浏览: 42
如果您希望在已有的数据中添加从爬取的数据中获取的一列数据,您可以使用以下代码示例:
```python
import os
import sqlite3
from bs4 import BeautifulSoup
import re
# 指定文件夹路径
folder_path = "C:/Users/test/Desktop/DIDItest"
# 正则表达式模式
pattern = r'<body>(.*?)</body>'
# 连接数据库
conn = sqlite3.connect('chat_data.db')
cursor = conn.cursor()
# 添加新的列
cursor.execute("ALTER TABLE chat_data ADD COLUMN new_column TEXT")
# 遍历文件夹中的所有文件
for root, dirs, files in os.walk(folder_path):
for file in files:
# 读取html文件
file_path = os.path.join(root, file)
with open(file_path, "r", encoding="utf-8-sig") as f:
html_code = f.read()
# 创建BeautifulSoup对象
soup = BeautifulSoup(html_code, 'html.parser')
# 使用正则表达式匹配<body>标签内的数据
body_data = re.findall(pattern, html_code, re.DOTALL)
# 剔除<p>和()</p>
body_data = body_data[0].replace("<p>", "").replace("()</p>", "")
# 使用正则表达式提取爬取的数据
new_data = re.findall(r'your_pattern', body_data)
# 处理匹配结果并更新数据库
for i, match in enumerate(matches):
talk_id = match[0]
new_column_data = new_data[i] # 根据匹配的索引获取对应的新数据
# 更新数据库中的新列数据
cursor.execute("UPDATE chat_data SET new_column = ? WHERE talk_id = ?", (new_column_data, talk_id))
# 提交事务并关闭连接
conn.commit()
conn.close()
print("---新列数据已添加到数据库中---")
```
请注意,您需要将代码中的`your_pattern`替换为您实际的正则表达式模式,以匹配您想要从爬取的数据中提取的内容。此外,您还需要根据您的实际情况修改文件夹路径、数据库连接和表格列名等部分。