【问题标题】:Seek to understand the Scrapy Callback寻求理解 Scrapy 回调
【发布时间】:2015-01-27 03:04:42
【问题描述】:

我正在尝试掌握 Scrapy Callback 的概念。我无法找到任何适合我的问题的答案,因为我需要在两个部分中产生两次项目并且还能够回调。

这是我的蜘蛛:

import scrapy
import csv

from scrapycrawler.items import DmozItem
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.selector import Selector
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request


class DmozSpider(CrawlSpider):
   name = "dmoz"
   allowed_domains = ["snipplr.com"]


def start_requests(self):
    #for i in xrange(1000):
    for i in range(1, 1000):
        yield self.make_requests_from_url("http://www.snipplr.com/all/page/%d" % i)

def parse(self, response):
    for sel in response.xpath('//ol[@class="snippets marg"]/li[1]/h3'):
        item = DmozItem()
        item['title'] = sel.xpath('a/text()').extract()
        item['link'] = sel.xpath('a/@href').extract()
        return Request(item['link'],  request.meta={'item':item}, callback=self.parse2)
        yield item

def parse2(self, response):
    for sel in response.xpath('//div[@class="description"]'):
        item = response.meta["item"]            
        item['desc'] = sel.xpath('p/text()').extract()
        yield item

这是我的管道:

import csv
from scrapy.exceptions import DropItem
from scrapy import log
import sys
import mysql.connector

class CsvWriterPipeline(object):

    def __init__(self):
        self.connection = mysql.connector.connect(host='localhost', user='sq', passwd='rt', db='sq')
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        self.cursor.execute("SELECT title,url FROM items WHERE title= %s", item['title'])
        result = self.cursor.fetchone()
        if result:

            log.msg("Item already in database: %s" % item, level=log.DEBUG)
        else:
            self.cursor.execute(
               "INSERT INTO items (title, url) VALUES (%s, %s, %s)",
                    (item['title'][0], item['link'], item['desc'][0]))
            self.connection.commit()

            log.msg("Item stored : " % item, level=log.DEBUG)
        return item

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

i am basically trying to get the data both from the first page and the page there after the page has been crawled. I am using Scrapy webcrawler an mysql. 

【问题讨论】:

    标签: python mysql callback scrapy web-crawler


    【解决方案1】:

    你只需要yieldRequest,而不是return

    def parse(self, response):
        for sel in response.xpath('//ol[@class="snippets marg"]/li[1]/h3'):
            item = DmozItem()
            item['title'] = sel.xpath('a/text()').extract()
            item['link'] = sel.xpath('a/@href').extract()
            yield Request(item['link'],  request.meta={'item':item}, callback=self.parse2)
            yield item
    

    【讨论】:

    • 好的,这样做但有一个关键错误,项目存在,管道也存在。
    • 好的,这样做但有一个关键错误,项目存在,管道也存在。这是蜘蛛和管道分别的代码:hastebin.com/doyexejazu.py 错误:return self._values[key] exceptions.KeyError: 'descs'
    • 如果需要参考,这是 Items 类,谢谢。导入scrapy class DmozItem(scrapy.Item): title = scrapy.Field() link = scrapy.Field() descs = scrapy.Field()
    • @CharlieC 我认为您不需要从 parse() 回调中产生项目。
    • @Alex e 但这将不允许我从第一阶段检索项目吗?
    猜你喜欢
    • 2016-11-21
    • 2014-05-04
    • 2015-02-25
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2017-08-30
    相关资源
    最近更新 更多