我是编码的初学者,如果我犯了任何错误,我深表歉意。我在网上抓取了一个网站并从中得到了一个表格列表。我正在尝试使用 for 循环将该数据插入到 sqlite 3 中,但返回时出现错误。import requestsfrom bs4 import BeautifulSoupimport json##from tkinter import *##bobert=Tk()##bobert.geometry("600x600")import sqlite3##cursor.execute("CREATE TABLE IF NOT EXISTS covid (name STRING, passward STRING, score INTEGER)")connection = sqlite3.connect('covidproject.db')cursor = connection.cursor()##cursor.execute("DROP TABLE IF EXISTS covid ")##cursor.execute("CREATE TABLE IF NOT EXISTS covid (name STRING, confirmed REAL, changes_today REAL,deceased REAL,active REAL, recovered REAL)")url = 'https://ncov2019.live/'headers = {'User-Agent':'Mozilla/5.0'}response = requests.get(url, headers = headers)response.status_codesoup = BeautifulSoup(response.content,'html.parser')stat_table = soup.find_all("table", attrs={"class": "display responsive"})headers = [header.get_text(strip=True) for header in soup.find_all("th")]rows = [dict(zip(headers, [td.get_text(strip=True) for td in row.find_all("td")])) for row in soup.find_all("tr")[1:-1]]for i,x in enumerate(rows,9): cursor.execute("INSERT INTO covid VALUES('"+rows[i]['Name']+"','"+rows[i]['Confirmed']+"','"+rows[i]['Changes Today']+"','"+rows[i]['Deceased']+"','"+rows[i]['Active']+"','"+rows[i]['Recovered']+"')") connection.commit()##print (json.dumps(rows[9], indent=2))##row2=rows[9]##print (rows[9]['Name'])##print (rows[9])这是错误:Traceback (most recent call last): File "C:\Users\minio\Downloads\sqlite-tools-win32-x86-3310100\sqlite-tools-win32-x86-3310100\webscraping3.py", line 31, in <module> cursor.execute("INSERT INTO covid VALUES('"+rows[i]['Name']+"','"+rows[i]['Confirmed']+"','"+rows[i]['Changes Today']+"','"+rows[i]['Deceased']+"','"+rows[i]['Active']+"','"+rows[i]['Recovered']+"')")KeyError: 'Name'
1 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
错误消息KeyError: 'Name'
表明您的词典没有“名称”键。你可以做几件事来诊断它;
首先要做的最简单的事情就是检查基本情况,它是否有名称条目。IE
print( rows[0]['Name'] )
如果可行,您可能想要做的下一件事是获得有关哪一行失败的更好信息,这样的事情可能可行:
for i,x in enumerate(rows,9): print( rows[i]['Name'] ) cursor.execute("INSERT INTO covid VALUES('"+rows[i]['Name']+"','"+rows[i]['Confirmed']+"','"+rows[i]['Changes Today']+"','"+rows[i]['Deceased']+"','"+rows[i]['Active']+"','"+rows[i]['Recovered']+"')") connection.commit()
您还可以使用像https://realpython.com/python-debugging-pdb/这样的教程,使用 Python 调试器单步执行代码。或者,您可以考虑使用 try/except 来忽略特定错误。
添加回答
举报
0/150
提交
取消