Python MySQL 数据插入

Python MySQL data insert

我正在尝试使用 pythonbeautifulsoup4 抓取页面。它将从该页面输出标题、价格、link。

从这 4 个 for 循环中,我想将这四个变量 imghref, href, name, newprice 插入到 MySQL 数据库中。所以我写了一些这样的代码:

    db = MySQLdb.connect("host", "root", "pass", "dbname")
    cursor = db.cursor()

    def sample(max_pages):
        page = 1
        while page <= max_pages:

            .... other lines, not related to mysql...

            for link in soup.findAll('a', {'class': 'hoverbuy a-color'}):
                href = link.get('href')
                #print(href)

            for title in soup.findAll('span', {'class': 'title ellipsis'}):
                name = title.string
                #print(name)

            for price in soup.find_all('div', {'class': 'itm-price'}):
                fprice= price.get_text() 
                newprice = fprice.replace("৳", "")
                #print(newprice)

            sql = "INSERT INTO product(link, title,price) \
                      VALUES ('%s', '%s', '%s')" % (href, name, newprice)

            try:  
               cursor.execute(sql)
               db.commit()
            except:
               db.rollback()      

            page += 1

    sample(1)

    db.close()

因此,当我 运行 这段代码时,只有一行(link、标题、价格)被插入到 MySQL 中,而其中有 70 行或更多那个页面。

所以,我认为 while 循环没有正确 运行 或者我错放了 sql 查询和 page += 1 循环

但如果我只打印这些变量,它 运行 与所有 70+ 输出完美结合

maxpages = 1,而page <= maxpages,循环可以运行。 当page+=1,page=2. 打破循环。 所以 sql 只执行一次。

href, name, newprice 为单值。所以只有一个记录。你应该使用 executemany() 来插入多条记录。

目前您 运行 只有 1 个 SQL 查询只插入 1 行。我猜它只会插入网站上的最后一个值。

目前您找到网站上每个项目的所有出现并替换您的 for 循环中的最后一个。 我建议将它们全部存储在一个列表中。然后将找到的所有内容添加到列表中。

for link in soup.findAll('a', {'class': 'hoverbuy a-color'}):
    href.append(link.get('href'))

for title in soup.findAll('span', {'class': 'title ellipsis'}):
    name.append(title.string)

for price in soup.find_all('div', {'class': 'itm-price'}):
    fprice= price.get_text() 
    newprice.append(fprice.replace("৳", ""))

您可能正在寻找的是 executemany() 方法。这允许您将整个列表放入数据库。或者,您可以查看我制作的有关如何执行此操作的视频,linked to specific time.

cursor.executemany("INSERT INTO product VALUES(?,?,?)",(href, name, newprice))

编辑:您可能要小心并确保所有列表的大小相同!