python - 如何使包含两个元组的变量进入 SQLite3 表?
问题描述
所以我从网站上抓取了一些场地名称和地址,现在我想使用函数将它们都添加到数据库表中。
不幸的是,incorrect bindings
每当我尝试对一组以上的元素执行此操作时,都会出现错误。当我只填充一列时,代码有效,但现在我试图填充两者都不起作用。我想知道这是否与我如何构建testsuburb
包含两个元组作为元组的变量有关...我一直在关注本教程(相关部分在底部),但它们使用手动输入的数据我正在尝试使用抓取的数据。
我将不胜感激任何指导!
这是网络抓取代码:
#cafeNames
url = 'https://www.broadsheet.com.au/melbourne/guides/best-cafes-thornbury' #go to the website
response = requests.get(url, timeout=5)
soup_cafe_names = BeautifulSoup(response.content, "html.parser")
type(soup_cafe_names)
cafeNames = soup_cafe_names.findAll('h2', attrs={"class":"venue-title", }) #scrape the elements
cafeNamesClean = [cafe.text.strip() for cafe in cafeNames] #clean the elements
cafeNameTuple = [(cafe,) for cafe in cafeNamesClean]
#addresses
soup_cafe_addresses = BeautifulSoup(response.content, "html.parser")
type(soup_cafe_addresses)
cafeAddresses = soup_cafe_addresses.findAll( attrs={"class":"address-content" })
cafeAddressesClean = [address.text for address in cafeAddresses]
cafeAddressesTuple = [(address,) for address in cafeAddressesClean]
#suburbtuple
testsuburb = [(cafeNameTuple), (cafeAddressesTuple)]
print(testsuburb)
这是功能:
##enter data into table
def insertnames(suburb):
try:
sqlite_insert_name_param = """INSERT INTO Thornbury
(name, address)
VALUES (?,?);"""
cursor.executemany(sqlite_insert_name_param, suburb)
sqliteConnection.commit()
print("Total", cursor.rowcount, "Records inserted successfully into table")
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("The SQLite connection is closed")
insertnames(testsuburb)
解决方案
您正在传递(单元素)元组列表;一层太多,形状相反。
你可能想要的是:suburb = zip(cafeNamesClean, cafeAddressesClean)
推荐阅读
- javascript - 在 javascript 中评估一个 Ascii 数学问题
- javascript - 如何解决基本组件中的 ReactJS 错误
- java - 异常 java.lang.OutOfMemoryError: Java 堆空间出现在递归中
- css - @font-face 接受的字体是否有一些限制?
- jquery - JQuery 和表格
- typescript - 使用 Mongoose 和 NestJS 的强类型模型
- javascript - 在 SAP CPI 中为要作为电子邮件附件发送的文件设置密码
- azure-pipelines - 在 azure 管道作业之间共享文件
- xml - 如何理解 xslt 语法 [not(.=preceding::*)]
- c# - 如何在没有数据库的情况下在 ASP.NET Core 中创建简单的登录并授权控制器访问