2011-12-10 73 views
0

所以我在玩Scrapy,這是一組允許你做網頁抓取的類,我想把一些數據放到數據庫中,但是我在擴展scrapy庫的時候會導入MySQL方法。如果你在Python中擴展一個類,你如何導入另一個類並使用它?

這裏是我的代碼:

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from scrapy.http import Request 
import MySQLdb 

class test(BaseSpider): #if i don't extend the class the MySQL works, but the Scrapy functionallity does not. 
    name = "test" 
    allowed_domains = ["some-website.com"] #i know this is probibly not a real websit... just using it as an example. 
    start_urls = [ 
     "http://some-website.com", 
    ] 

    db = MySQLdb.connect(
     host = 'localhost', 
     user = 'root', 
     passwd = '', 
     db = 'scrap' 
    ) 
    #cursor = db.cursor() 

    def parse(self, response): 
     hxs = HtmlXPathSelector(response) 
     for title in hxs.select('//a[@class="title"]/text()').extract(): 
      print title 
      cursor.execute("INSERT INTO `scrap`.`shows` (id, title) VALUES (NULL , '"+title+"');") 

我還是一個菜鳥到Python所以任何幫助將不勝感激。

+0

你能解決你的縮進問題嗎? –

回答

3

有些事情不對您architecture

Spider的工作是解析頁面,提取數據並將其放入Item。這是pipeline's工作,從項目保存在數據庫中的數據:

的項目管道典型用途是:

  • 清理HTML數據
  • 驗證刮數據(檢查項目包含某些字段)
  • 爲重複檢查(以及丟棄它們)
  • 存儲在數據庫刮下項

因此,製作一條管線,將其路徑放入settings.py。嘗試在該管道中使用數據庫。

我認爲您需要閱讀tutorial並查看examples

+0

非常感謝您收到此提示。就像我之前說過的,當談到python時,我還是一個noob。我會考慮建立一條管道。 –

0

也許你的確定義self.cursor
通過這種方式,遊標可以在類方法上訪問。 我不知道scrapy,但最有可能你應該做的是在__init__方法或類測試的方法get_cursor(即可能是你應該改名爲測試)

相關問題