【问题标题】:Scrapy Deploy Doesn't Match Debug ResultScrapy Deploy 与调试结果不匹配
【发布时间】:2014-10-21 06:21:38
【问题描述】:

我正在使用 Scrapy 从网站中提取一些数据,例如“myproject.com”。逻辑如下:

  1. 进入首页,有一些categorylist是用来搭建第二波链接的。
  2. 对于第二轮链接,它们通常是每个类别的第一页。此外,对于该类别中的不同页面,它们遵循相同的正则表达式模式wholesale/something/something/request or wholesale/pagenumber。我想按照这些模式继续爬行,同时将原始 HTML 存储在我的项目对象中。

我使用parse 分别测试了这两个步骤,它们都有效。

首先,我试过了:

scrapy parse http://www.myproject.com/categorylist/cat_a --spider myproject --rules 

我可以看到它成功地建立了外链。然后我再次测试了构建的外链。

scrapy parse http://www.myproject.com/wholesale/cat_a/request/1 --spider myproject --rules

而且似乎规则是正确的,它会生成一个带有 HTML 存储在其中的项目。

但是,当我尝试使用 depth 参数将这两个步骤链接在一起时。我看到它爬取了外链,但没有生成任何项目。

scrapy parse http://www.myproject.com/categorylist/cat_a --spider myproject --rules --depth 2

这是伪代码:

class MyprojectSpider(CrawlSpider):
    name = "Myproject"
    allowed_domains = ["Myproject.com"]
    start_urls = ["http://www.Myproject.com/"]

    rules = (
        Rule(LinkExtractor(allow=('/categorylist/\w+',)), callback='parse_category', follow=True),
        Rule(LinkExtractor(allow=('/wholesale/\w+/(?:wholesale|request)/\d+',)), callback='parse_pricing', follow=True),
    )

    def parse_category(self, response):
        try:
            soup = BeautifulSoup(response.body)
            ...
            my_request1 = Request(url=myurl1)
            yield my_request1
            my_request2 = Request(url=myurl2)
            yield my_request2
        except:
            pass

    def parse_pricing(self, response):
        item = MyprojectItem()
        try:
            item['myurl'] = response.url
            item['myhtml'] = response.body
            item['mystatus'] = 'fetched'
        except:
            item['mystatus'] = 'failed'
        return item

非常感谢您的任何建议!

【问题讨论】:

    标签: python regex web-scraping scrapy web-crawler


    【解决方案1】:

    我假设我构建的新 Request 对象将针对 rules 运行,然后由规则中定义的相应回调函数解析,但是,在读取请求的 documentation 后,@987654324 @ 方法的处理方式不同。

    class scrapy.http.Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8', priority=0, dont_filter=False, errback])

    callback (callable) – 将调用此请求的响应(一旦下载)作为其第一个参数的函数。有关更多信息,请参阅下面的将附加数据传递给回调函数。 如果请求没有指定回调,将使用蜘蛛的 parse() 方法。请注意,如果在处理过程中引发异常,则会调用 errback。

    ...
    my_request1 = Request(url=myurl1, callback=self.parse_pricing)
    yield my_request1
    my_request2 = Request(url=myurl2, callback=self.parse_pricing)
    yield my_request2
    ...
    

    换一种方式,即使我建立的网址符合第二条规则,也不会传递给parse_pricing。希望这对其他人有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多