python使用数据库时,关闭游标报错,如何解决?
源码如下:
from selenium.webdriver import Chrome, ChromeOptions
import pymysql
class SQL:
def __init__(self):
self.host = 'localhost'
self.username = 'root'
self.password = '199904300073'
self.database = 'lvyouxitong'
self.conn = None
self.cursor = None
def connect(self):
self.conn = pymysql.connect(host=self.host, port=3306,user=self.username, password=self.password, database=self.database)
def execute(self, str):
if self.conn is None:
self.connect()
self.cursor = self.conn.cursor()
self.cursor.execute(str)
self.conn.commit()
def query(self, str):
if self.conn is None:
self.connect()
self.cursor = self.conn.cursor()
self.cursor.execute(str)
return self.cursor.fetchall()
def close(self):
self.cursor.close()
self.conn.close()
option = ChromeOptions()
option.add_argument('--headless')
option.add_argument('--no-sandbox')
url = 'https://new.qq.com/ch/visit/'
browser = Chrome(options=option)
browser.get(url=url)
sql = SQL()
browser_list = browser.find_elements_by_xpath('//*[@id="dataFull"]/li/h3/a')
for i in browser_list:
title = i.text
url = i.get_attribute('href')
sql.execute('insert into hot_news values(0, "%s", "%s");' % (title, url))
print('%s -插入成功' % title)
sql.close()
可以参考这篇文章看下,https://ask.csdn.net/questions/7702815 检查下你的sql
不对了 检查日志
页:
[1]