You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将BeautifulSoup抓取的数据存入SQLite数据库

错误原因

  • SQLite的参数占位符不支持%s格式,你需要使用SQLite指定的?作为占位符
  • cur.execute的第二个参数要求传入元组类型,直接传入字符串会触发参数不匹配错误
  • 数据库关闭操作con.close()写在for循环内部,第一次插入完成后连接就会被关闭,后续循环的插入操作全部失效

修复后的完整代码

from flask import Flask
import requests
from bs4 import BeautifulSoup
import sqlite3


con=sqlite3.connect('scrap.db')
cur=con.cursor()
      
cur.execute('''CREATE TABLE IF NOT EXISTS headers (
            header text
            ) ''')

# 增加UA头避免被目标网站反爬拦截
req_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
req=requests.get('https://www.reddit.com/?ref=upstract.com&curator=upstract.com&utm_source=upstract.com', headers=req_headers)
req.status_code

soup=BeautifulSoup(req.content,'html.parser')
contentRedid=soup.find_all("h3",{"class":"_eYtD2XCVieq6emjKBH3m"})
for content in contentRedid:
      header_text = content.getText().strip()
      # 替换占位符为?,参数包裹为单元素元组
      query='INSERT INTO headers VALUES (?)'
      cur.execute(query, (header_text,)) 
      con.commit()

# 关闭操作移到循环外部
con.close()

# print(contentRedid)
app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

内容的提问来源于stack exchange,提问作者Micheal841

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:57:02