BeautifulSoup爬取数据存入MySQL仅插入1条记录,求问题排查
为什么修改后的爬虫代码只插入了1条数据?
嘿,我帮你揪出问题啦!核心问题出在你获取商品列表的选择器上:
你写的这行代码:
recordList = bsObj.findAll("div", {"class": "wrap overflow", })
它拿到的不是单个商品的条目,而是整个商品列表的父容器(这个页面里符合wrap overflow的div只有1个),所以你的for record in recordList循环只会执行一次,自然也就只插入了1条数据。
修复步骤
你需要找到页面中单个商品对应的HTML元素作为循环对象。可以用浏览器开发者工具查看目标页面的元素结构,每个商品通常会有专属的容器类名,比如item-box或者item-wrap这类(具体以实际页面结构为准)。
给你一个修正后的代码示例:
from urllib import urlopen from bs4 import BeautifulSoup import pymysql.cursors html = urlopen("https://www.banggood.com/Wholesale-Computer-and-Networking-c-155.html") bsObj = BeautifulSoup(html, "html.parser") # 替换成单个商品的容器选择器,这里以item-box为例,你可根据实际页面调整 recordList = bsObj.findAll("div", {"class": "item-box"}) connection = pymysql.connect(host='localhost', user='root', password='', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: for record in recordList: # 确保在单个商品元素内能找到对应的标题和价格元素 title_elem = record.find("span", {"class": 'title'}) title = title_elem.get_text().strip() if title_elem else "无标题" price_elem = record.find("span", {"class": "price wh_cn"}) price = price_elem.get_text().strip() if price_elem else "无价格" sql = "INSERT INTO `artist_song` (`artist`, `song`) VALUES (%s, %s)" # 小提醒:变量名artist实际存的是价格,建议改成price更清晰 cursor.execute(sql, (price, title)) connection.commit() finally: connection.close()
额外小建议
- 给
find方法加个空值判断,避免页面结构变动时找不到元素抛出异常,让代码更健壮; - 变量名
artist实际存储的是商品价格,建议改成price,避免后续维护时混淆。
内容的提问来源于stack exchange,提问作者Reezal AQ
相关产品推荐
相关产品推荐

