不绝今生 2022-05-05 17:39 采纳率: 100%
浏览 131
已结题

爬虫爬取数据成功后只在运行窗口出现数据却并没有存储到数据库是什么原因?

问题是,将爬取的数据保存到数据库里,但是运行后数据只在运行窗口出现,而没有存储到数据库里

from urllib.request import urlopen,Request
from bs4 import BeautifulSoup
import re
import pymysql
for a in range(10):
    head = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Mobile Safari/537.36 Edg/100.0.1185.39"}
    url = "https://movie.douban.com/top250?start={}&filter=".format(a*25)
    request = Request(url, headers=head)
    respose = urlopen(request)
    html = respose.read().decode()
    # 连接数据库
    connect = pymysql.Connect(
        host='localhost',
        port=3306,
        user='root',
        password='201314t',
        db='spider_test',
        charset='utf8'
    )
    findImg = re.compile(r'<img.*src="(.*?)"', re.S)
    findTitle = re.compile(r'<span class="title">(.*)</span>')
    findScore = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
    findPl = re.compile(r'<span>(.*)</span>')
    soup = BeautifulSoup(html, "html.parser")
    for item in soup.find_all('div', class_="item"):
        item = str(item)

        imgSrc = re.findall(findImg, item)[0]
        titles = (re.findall(findTitle, item)[0]).split()[0]
        score = re.findall(findScore, item)[0]
        pl = re.findall(findPl, item)[0]
        data = (imgSrc,titles,score,pl)
        print(data)

        #获取游标
        cursor = connect.cursor()

        #执行插入语句
        sql = "INSERT INTO douban_movie(img_src,pc_name,score,pl) VALUES (%s,%s,%s,%s)"
        # cursor.execute(sql,[data])
        cursor.close()
        connect.commit()
connect.close()

运行结果及报错内容

img

数据库

img

不知道是什么原因?数据库是连接上的,没有问题。在倒数第四行代码,没有注释的情况下直接错误

img

  • 写回答

1条回答 默认 最新

  • 卑以自牧w 2022-05-05 18:17
    关注

    错误在最后一个文件的第125行吗,而且最后说明了错误的原因 哈哈哈

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 6月29日
  • 已采纳回答 6月21日
  • 创建了问题 5月5日

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)