1

我试图让scrapy将抓取的数据插入mysql,我的代码抓取良好并收集缓冲区中的数据,不会出错,但数据库永远不会更新。'没有运气','没有错误'

管道.py

from twisted.enterprise import adbapi
import datetime
import MySQLdb.cursors

class SQLStorePipeline(object):

    def __init__(self):
        self.dbpool = adbapi.ConnectionPool('MySQLdb', db='craigs',
                user='bra', passwd='boobs', cursorclass=MySQLdb.cursors.DictCursor,
                charset='utf8', use_unicode=True)

    def process_item(self, items, spider):
        # run db query in thread pool
        query = self.dbpool.runInteraction(self._conditional_insert, items)
        query.addErrback(self.handle_error)

        return items

    def _conditional_insert(self, tx, items):
        # create record if doesn't exist.
        # all this block run on it's own thread
        tx.execute("select * from scraped where link = %s", (items['link'][0], ))
        result = tx.fetchone()
        if result:
            log.msg("Item already stored in db: %s" % items, level=log.DEBUG)
        else:
            tx.execute(\
                "insert into scraped (posting_id, email, location, text, title) "
                "values (%s, %s, %s, %s, %s)",
                (items['posting_id'][0],
                items['email'][1],
                items['location'][2],
                items['text'][3],
                items['title'][4],
                )

            )
            log.msg("Item stored in db: %s" % items, level=log.DEBUG)

    def handle_error(self, e):
        log.err(e)

爬取代码

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from craigs.items import CraigsItem

class MySpider(CrawlSpider):
    name = "craigs"
    f = open("urls.txt")
    start_urls = [url.strip() for url in f.readlines()]
    f.close()
    rules = [Rule(SgmlLinkExtractor(restrict_xpaths=('/html/body/blockquote[3]/p/a',)), follow=True, callback='parse_profile')]

    def parse_profile(self, response):
        items = []
        img = CraigsItem()
        hxs = HtmlXPathSelector(response)
        img['title'] = hxs.select('//h2[contains(@class, "postingtitle")]/text()').extract()
        img['posting_id'] = hxs.select('//html/body/article/section/section[2]/div/p/text()').extract()
        items.append(img)
        return items[0]
        return img[0]

设置.py

BOT_NAME = 'craigs' 
BOT_VERSION = '1.0' 
SPIDER_MODULES = ['craigs.spiders'] 
NEWSPIDER_MODULE = 'craigs.spiders' 
USER_AGENT = '%s/%s' % (BOT_NAME, BOT_VERSION)
4

3 回答 3

1

管道代码根本没有被调用的原因是它没有被激活。根据文档中的 Item Pipelines 页面,此激活是通过向 settings.py 添加一个新部分来完成的。例如

ITEM_PIPELINES = [
    'craigs.pipeline.SQLStorePipeline',
]

此外,您的parse_profile函数应该只返回img. 如果单个响应页面会导致多个项目,您只会添加要返回的项目列表。

于 2013-02-10T12:52:04.557 回答
1

在设置中激活 Pipeline 并使用 yield 而不是 return

于 2013-08-19T15:11:20.447 回答
0

您应该COMMIT当前事务,这使得更改永久。

所以之后

tx.execute(\
            "insert into scraped (posting_id, email, location, text, title) "
            "values (%s, %s, %s, %s, %s)",
            (items['posting_id'][0],
            items['email'][1],
            items['location'][2],
            items['text'][3],
            items['title'][4],
            )

        )

你必须

db.commit()

db这是类似的东西

db = MySQLdb.connect(host="localhost",user = "root", passwd = "1234", db="database_name")

请尝试一下。

于 2014-05-24T12:18:18.373 回答