【问题标题】:use pymysql to insert table使用 pymysql 插入表
【发布时间】:2017-03-23 14:04:12
【问题描述】:

我正在解析一个网站并想插入到 MySQL。有 6 个字段需要解析特定字段下的每个 url。 有人知道我如何使用 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

【问题讨论】:

  • 当你运行这段代码时会发生什么?输出?您到底在寻找什么?
  • @r0xette 这里是接收 Traceback 的内容(最近一次调用最后一次):文件“C:/PycharmProjects/untitled4/m_new.py”,第 22 行,在 cursor.execute("INSERT INTO微 (d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn'], d['ean'], ) 值 (%s, %s,%s,%s,%s,%s)",(d['brand'], d['productPrice'], d['SKU'], d['productID'], d['mpn '], d['ean'])) 类型错误:字符串索引必须是整数
  • 您没有从 mysql 读取数据,因此您的问题“我如何使用 pymysql 将 MySQL 表转换为字典对象”没有任何意义

标签: python mysql web-scraping pymysql


【解决方案1】:

您的 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']))

【讨论】:

  • 仍然出现同样的错误,TypeError: string indices must be integers.
猜你喜欢
  • 2017-06-11
  • 2019-07-13
  • 2013-12-27
  • 1970-01-01
  • 2019-01-01
  • 2021-01-12
  • 2015-04-13
  • 2019-02-19
  • 1970-01-01
相关资源
最近更新 更多