2017-04-27 95 views
0

我正在尝试使用Scrapy为大学项目构建一个小应用程序。 蜘蛛抓取的项目,但我的管道没有插入数据到MySQL数据库。为了测试管道是否不工作或pymysl执行不工作我写了一个测试脚本:Scrapy管道不插入到MySQL

代码开始

#!/usr/bin/python3 

import pymysql 

str1 = "hey" 
str2 = "there" 
str3 = "little" 
str4 = "script" 

db = pymysql.connect("localhost","root","**********","stromtarife") 

cursor = db.cursor() 

cursor.execute("SELECT * FROM vattenfall") 
cursor.execute("INSERT INTO vattenfall (tarif, sofortbonus, treuebonus, jahrespreis) VALUES (%s, %s, %s, %s)", (str1, str2, str3, str4)) 
cursor.execute("SELECT * FROM vattenfall") 
data = cursor.fetchone() 
print(data) 
db.commit() 
cursor.close() 

db.close() 

代码结束

我运行之后脚本我的数据库有一个新的记录,所以它不是我的pymysql.connect()函数,这是破产。

我会提供我scrapy代码:

vattenfall_form.py

# -*- coding: utf-8 -*- 
import scrapy 
from scrapy.crawler import CrawlerProcess 
from stromtarife.items import StromtarifeItem 

from scrapy.http import FormRequest 

class VattenfallEasy24KemptenV1500Spider(scrapy.Spider): 
    name = 'vattenfall-easy24-v1500-p87435' 

    def start_requests(self): 
     return [ 
      FormRequest(
       "https://www.vattenfall.de/de/stromtarife.htm", 
       formdata={"place": "87435", "zipCode": "87435", "cityName": "Kempten", 
         "electricity_consumptionprivate": "1500", "street": "", "hno": ""}, 
      callback=self.parse 
     ), 
    ] 

    def parse(self, response): 
     item = StromtarifeItem() 
     item['jahrespreis'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[3]/td[2]/text()').extract_first() 
     item['treuebonus'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[2]/td/strong/text()').extract_first() 
     item['sofortbonus'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[1]/td/strong/text()').extract_first() 
     item['tarif'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[1]/h2/span/text()').extract_first() 
     yield item 



class VattenfallEasy24KemptenV2500Spider(scrapy.Spider): 
    name = 'vattenfall-easy24-v2500-p87435' 

    def start_requests(self): 
     return [ 
        FormRequest(
        "https://www.vattenfall.de/de/stromtarife.htm", 
        formdata={"place": "87435", "zipCode": "87435", "cityName": "Kempten", 
           "electricity_consumptionprivate": "2500", "street": "", "hno": ""}, 
        callback=self.parse 
       ), 
    ] 

    def parse(self, response): 
     item = StromtarifeItem() 
     item['jahrespreis'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[3]/td[2]/text()').extract_first() 
     item['treuebonus'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[2]/td/strong/text()').extract_first() 
     item['sofortbonus'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[2]/form[1]/div/div[2]/table/tbody/tr[1]/td/strong/text()').extract_first() 
     item['tarif'] = response.xpath('/html/body/main/div[1]/div[2]/div/div[3]/div[2]/div/div[1]/h2/span/text()').extract_first() 
     yield item 



process = CrawlerProcess() 
process.crawl(VattenfallEasy24KemptenV1500Spider) 
process.crawl(VattenfallEasy24KemptenV2500Spider) 
process.start() 

pipelines.py

import pymysql 
from stromtarife.items import StromtarifeItem 


class StromtarifePipeline(object): 
    def __init__(self): 
     self.connection = pymysql.connect("localhost","root","**********","stromtarife") 
     self.cursor = self.connection.cursor() 


    def process_item(self, item, spider): 
     self.cursor.execute("INSERT INTO vattenfall (tarif, sofortbonus, treuebonus, jahrespreis) VALUES (%s, %s, %s, %s)", (item['tarif'], item['sofortbonus'], item['treuebonus'], item['jahrespreis'])) 
     self.connection.commit() 
     self.cursor.close() 
     self.connection.close() 

settings.py(我改变了只有一行)

ITEM_PIPELINES = { 
    'stromtarife.pipelines.StromtarifePipeline': 300, 
} 

那么,什么是错我的代码?我无法弄清楚,如果有人看到我错过的东西,我会很开心。提前致谢!

回答

1

每次处理项目时都不应关闭pymsql连接。

你应该写的close_spider功能在您的管道这样的,所以在连接关闭只有一次,在执行结束:

def close_spider(self, spider): 
     self.cursor.close() 
     self.connection.close() 

而且你neeed到的process_item末退回商品

您的文件pipeline.py应该是这样的:

import pymysql 
from stromtarife.items import StromtarifeItem 


class StromtarifePipeline(object): 
    def __init__(self): 
     self.connection = pymysql.connect("localhost","root","**********","stromtarife") 
     self.cursor = self.connection.cursor() 


    def process_item(self, item, spider): 
     self.cursor.execute("INSERT INTO vattenfall (tarif, sofortbonus, treuebonus, jahrespreis) VALUES (%s, %s, %s, %s)", (item['tarif'], item['sofortbonus'], item['treuebonus'], item['jahrespreis'])) 
     self.connection.commit() 
     return item 

    def close_spider(self, spider): 
     self.cursor.close() 
     self.connection.close() 

UPDATE:

我想你的代码,问题是出在酝酿中,有两个问题:

  • 您尝试索引欧元符号,我觉得MySQL不喜欢它。
  • 您的查询字符串构建不当。

我设法把事情通过书面方式将管道这样做:

def process_item(self, item, spider): 
    query = """INSERT INTO vattenfall (tarif, sofortbonus, treuebonus, jahrespreis) VALUES (%s, %s, %s, %s)""" % ("1", "2", "3", "4") 
    self.cursor.execute(query) 
    self.connection.commit() 
    return item 

我的东西,你应该从你尝试插入价格取出

希望这有助于,让我知道。

+0

谢谢你的回答。我改变了process_item()并添加了close_spider(),但我仍然没有得到任何东西到我的数据库中。如果我得到结果,我可以进行下一步并遵循rrschmidt的建议。我真的不知道我的代码有什么问题.. – tolgaIsThere

+0

我在cursor.execute()函数中的process_item()中替换了部分: ...%s,%s)“,(item ['tarif'], item ['sofortbonus'],item ['treuebonus'],item ['jahrespreis'])) with strings: ..%s,%s)“,(”hey“,”how“,”are“ “你”)) 而且它仍然不工作.. – tolgaIsThere

+0

我更新了以前的答案,让我知道如果这适合你 –

0

除了SQL管道在写完第一个项目之后关闭SQL连接(如Adrien指出的)之外,还存在另一个问题。

另一个问题是:您的刮板只能为每个结果页面(并且只访问一个结果页面)的单个项目刮取一个。我检查了Vattenfall,通常会显示多个结果,我想你想把它们都刮掉。

意味着你还必须遍历页面上的结果,并创建多个项目,而这样做。这里的scrapy教程给出了一个很好的解释:https://doc.scrapy.org/en/latest/intro/tutorial.html#extracting-quotes-and-authors