Kokietry
Kokietry
2020-06-13 10:42
采纳率: 0%
浏览 1.0k

急!把爬取下来的数据存入到数据库显示'Cursor' object has no attribute 'rollback' 这是什么问题?

同样的代码在我室友的电脑上可以运行 但是我自己的就不行
不明白是数据库出问题还是pycharm出了问题 求大佬们指教
下面是错误
图片说明

代码也同样附上

import requests
from lxml import etree
import re
import pymysql

url=r"https://www.cncn.com/top/"
header={"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
def spiderMountain7414118208():
    jd=[]
    response=requests.get(url,headers=header).text
    html=etree.HTML(response)
    name=html.xpath('//div[@class="tit"]/h3/a/text()')
    href=html.xpath('//div[@class="tit"]/h3/a/@href')
    namehref = [(n,h) for n,h in zip(name, href) if h!= '']
    tup=namehref[0]
    print(tup)
    response = requests.get(tup[1],headers=header).content
    html = etree.HTML(response)
    for i in range(1,11):
        name = html.xpath('//div/li[@class="num{}"]/a/@title'.format(str(i)))
        href = html.xpath('//div/li[@class="num{}"]/a/@href'.format(str(i)))
        introduce = html.xpath('//div/p[@class="num{0}"]/font/text()|//div/p[@class="num{0}"]/font/font/text()'.format(str(i)))
        #print(name[0],href[0],introduce[0])
        tup1=(name[0],href[0],re.sub("\s\n\t","",introduce[0]))
        jd.append(tup1)
    return jd

def saveDB7414118208(lst):
    with pymysql.connect("localhost","root","1234","db7414118208") as conn:
        sqlInsert="insert into mountain7414118208 values(NULL,%s,%s,%s)"
        for item in lst:
            try:
                conn.execute(sqlInsert,item)
                print("{}景点信息保存成功".format(item[0]))
            except:
                conn.rollback()
                print("景点信息保存失败")
                conn.close()


def listAll7414118208():
    with pymysql.connect("localhost", "root", "1234", "db7414118208") as conn:
        sql1 = "SELECT mno,mname from mountain7414118208"
        conn.execute(sql1)
        alldata = conn.fetchall()
        print(alldata)
        conn.close()

def search7414118208():
    with pymysql.connect("localhost", "root", "1234", "db7414118208") as conn:
        sql2="SELECT mno,mname from mountain7414118208 where mno='%d'(mno)"
        print(sql2)

#主函数
if __name__=="__main__":
    jdlst=spiderMountain7414118208()
    print("爬取景点\n1.保存至数据库\n2.显示山编号、名称\n3.查询信息\n4.退出")
    while True:
        s=input("输入1-4的数字:")
        if s=="1":
            saveDB7414118208(jdlst)
        elif s=="2":
            listAll7414118208()
        elif s=="3":
            search7414118208(3)
        else:
            exit()
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy

    conn.rollback()
    重新输入下,看看是不是输错了字母
    或者conn根本就是NoneType,数据库连接失败了

    点赞 评论

相关推荐