在Python中,有許多庫(kù)可以用于進(jìn)行網(wǎng)絡(luò)爬蟲(chóng)和數(shù)據(jù)存儲(chǔ)。以下是一些建議的庫(kù)和方法:
open()
函數(shù)以讀寫(xiě)模式(‘w’或’a’)打開(kāi)一個(gè)文件,然后將數(shù)據(jù)寫(xiě)入文件中。例如:data = {"key": "value"}
with open("output.txt", "w") as file:
file.write(str(data))
import csv
data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
with open("output.csv", "w", newline='') as file:
writer = csv.DictWriter(file, fieldnames=["name", "age"])
writer.writeheader()
for row in data:
writer.writerow(row)
json
庫(kù)將數(shù)據(jù)存儲(chǔ)到JSON文件中。例如:import json
data = {"key": "value"}
with open("output.json", "w") as file:
json.dump(data, file)
import sqlite3
# 連接到數(shù)據(jù)庫(kù)(如果不存在,將創(chuàng)建一個(gè)新文件)
conn = sqlite3.connect("example.db")
# 創(chuàng)建一個(gè)游標(biāo)對(duì)象
cursor = conn.cursor()
# 創(chuàng)建一個(gè)表
cursor.execute("""
CREATE TABLE IF NOT EXISTS data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL,
value TEXT NOT NULL
)
""")
# 插入數(shù)據(jù)
data = {"key": "value"}
cursor.execute("INSERT INTO data (key, value) VALUES (?, ?)", (data["key"], data["value"]))
# 提交更改并關(guān)閉連接
conn.commit()
conn.close()
from elasticsearch import Elasticsearch
es = Elasticsearch()
data = {"key": "value"}
es.index(index="my_index", id=1, document=data)
根據(jù)你的需求和數(shù)據(jù)類(lèi)型,可以選擇合適的方法進(jìn)行數(shù)據(jù)存儲(chǔ)。