【发布时间】:2020-07-03 19:02:00
【问题描述】:
该项目的目标是从表中抓取数据并将结果放入 sqllite 数据库,但是我不知道我目前尝试的方式是否可行。目前数据存储在一个列表中,由表上的每一行分隔,唯一的问题是尝试将其插入数据库。我发现此代码的错误是 sql 插入的输入不完整。 我已经尝试在线搜索解决方案,但到目前为止没有任何帮助,它会导致此问题或列表索引超出范围。
from bs4 import BeautifulSoup
import requests
import sqlite3
headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"}
url = "https://en.wikipedia.org/wiki/Comparison_of_computer_viruses"
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[1]
rows = table.find_all('tr')
row_list= list()
for tr in rows:
td = tr.find_all('td')
row = [i.text for i in td]
row_list.append(row)
print(row_list)
print(row_list[1][1])
maldb = sqlite3.connect("maldb")
cursor = maldb.cursor()
cursor.execute('''drop table if exists mal''')
cursor.execute('''create table mal
(virus text primary key,
alias text,
typeof text,
subtype text,
isolation_date text,
isolation text,
origin text,
author text,
notes text)
''')
for z in range(1,95):
cursor.execute('''INSERT into mal ('?','?','?','?','?','?','?','?','?')''',(row_list[z][0],row_list[z][1],row_list[z][2],row_list[z][3],row_list[z][4],row_list[z][5],row_list[z][6],row_list[z][7],row_list[z][8]))
maldb.commit()
maldb.close()
【问题讨论】:
-
你最好从 Postgres 文档中检查 INSERT 语法。尝试缩小问题二相关异常,最终提供实际内容。
标签: python sqlite beautifulsoup