首页 > 解决方案 > 使用 Python 更新 Sqlite:InterfaceError:错误绑定参数 0 和 None 类型不可下标

问题描述

我已经抓取了一些网站并将 html 信息存储在 sqlite 数据库中。现在,我想提取和存储电子邮件地址。我能够成功提取并打印 id 和电子邮件。但是,当我尝试使用这些新的电子邮件地址更新数据库时,我不断收到 TypeError:“'NoneType' 对象不可下标”和“sqlite3.InterfaceError:错误绑定参数 0 - 可能不受支持的类型”。

我已经验证了我在更新语句中使用的数据类型与我的数据库相同(id 是 int 类,email 是 str)。我在谷歌上搜索了一堆不同的例子,并对语法进行了很多研究。

我还尝试在更新语句中删除 Where 子句,但得到了同样的错误。

import sqlite3
import re


conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()

x = cur.execute('SELECT id, html FROM Pages WHERE html is NOT NULL and email is NULL ORDER BY RANDOM()').fetchone()
#print(x)#for testing purposes

for row in x:
    row = cur.fetchone()
    id = row[0]
    html = row[1]

    email = re.findall(b'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', html)
    #print(email)#testing purposes
    if not email:
        email = 'no email found'

    print(id, email)
    cur.execute('''UPDATE pages SET email = ? WHERE id = ? ''', (email, id))


conn.commit

我希望更新语句使用提取的相应行的电子邮件地址更新数据库。

标签: python-3.xsqlite

解决方案


.findall()返回一个列表。您想遍历该列表:

    for email in re.findall(..., str(html)):
        print(id, email)
        cur.execute(...)

b'[a-z...'不知道那个表情是怎么回事。建议您改用原始字符串:r'[a-z...'. \它可以很好地处理正则表达式的倒退。


推荐阅读