2016-11-09 35 views
0

Im解析一個網站,並希望插入到MySQL。有6個字段需要在特定字段下解析每個網址。 任何人都知道我可以如何使用pymysql將一個MySQL錶轉換爲Python中的字典對象?使用pymysql來插入表

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 
+0

當您運行此代碼會發生什麼?輸出?你到底在找什麼? – r0xette

+0

@ r0xette這裏是什麼接收 回溯(最近呼叫最後): 文件「C:/PycharmProjects/untitled4/m_new.py」,第22行,在 cursor.execute(「INSERT INTO micro(d ['brand '],d ['productPrice'],d ['SKU'],d ['productID'],d ['mpn'],d ['ean'],)VALUES(%s,%s,%s, %'s','d','['品牌'],d ['productPrice'],d ['SKU'],d ['productID'],d ['mpn'],d [ ean'])) TypeError:字符串索引必須是整數 – Burak

+0

您沒有從MySQL讀取數據,因此您的問題「如何使用pymysql將MySQL錶轉換爲字典對象」沒有任何意義 – e4c5

回答

0

你的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'])) 
+0

同樣的錯誤,TypeError:字符串索引必須是整數。 – Burak