python - 使用pymysql插入表

标签 python mysql web-scraping pymysql

我正在解析一个网站并想要插入到 MySQL。特定字段下的每个url需要解析6个字段。 有人知道如何使用 pymysql 将 MySQL 表转换为 Python 中的字典对象吗?

from bs4 import BeautifulSoup
import requests
import urllib.request
import pymysql

con = pymysql.connect(host = 'localhost',user = 'root',passwd = 'root',db = 'm_db')
cursor = con.cursor(pymysql.cursors.DictCursor)

with open(r"C:\New folder\urllist.txt") as f:
    urls = [u.strip('\n') for u in f.readlines()]
    page = 0
    while page < 5:
        try:
            soup = BeautifulSoup(requests.get(urls[page]).content, "html.parser")
            text = soup.select("head script[type=text/javascript]")[-1].text
            start = text.find('dataLayer = [') + len('dataLayer = [')
            end = text.rfind('];')
            rows = text[start:end].strip().split('\n')
        except:
            pass
        for d in rows:
            cursor.execute("INSERT INTO micro (d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn'], d['ean'], ) VALUES (%s,%s,%s,%s,%s,%s)",(d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn'], d['ean']))
            d = cursor.fetchall()
        con.commit()
        page = page + 1

如何使用我拥有的数据填充 SQL 插入语句。 这是我的数据

{
     'brand':'Fluke',
     'productPrice':'2199.99',
     'SKU':'34353362',
     'productID':'443329',
     'mpn':'RT-AC3200',
     'ean':'886290480914',
}

它会产生此错误

Traceback (most recent call last): File "C:/PycharmProjects/untitled4/m_new.py", line 22, 
in <module> cursor.execute("INSERT INTO micro (d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn'], d['ean'], ) VALUES (%s,%s,%s,%s,%s,%s)",(d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn'], d['ean'])) 
TypeError: string indices must be integers

最佳答案

您的 SQL 查询不正确。应该是

cursor.execute("INSERT INTO micro (brand, productPrice, SKU, productID, mpn, ean) VALUES (%s,%s,%s,%s,%s,%s)",(d['brand'], d['productPrice'], d['SKU'], d['productID'],d['mpn'], d['ean']))

关于python - 使用pymysql插入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40512440/

相关文章:

python - "object layout"

python - 在列表中查找 ContiguousCount 项?

php - 创建没有多个 SQL 查询的 JSON 对象 (PHP)

mysql搜索类似于默认android联系人应用程序中的搜索

python - 如何从 Python 优雅地终止 GLib 主循环

python - Y 中的 X 太多

mysql - 获取类别级别

python - 从脚本中提取 - BeautifulSoup

javascript - 正则表达式捕获所有内容,而不仅仅是括号中的 "Wildcard"- 如何修复它?

python - 无法从福布斯抓取当天的报价