2012-08-30 2 views
3

나는 Scrapy에서 기본적으로 벌금을 내고 정확하게 수행하고있는 거미를 작성했다. 문제는 작은 변화가 필요하며 성공없이 여러 방법을 시도했습니다 (예 : InitSpider 수정). 여기에 스크립트가 지금 어떻게해야되는 것입니다 : 지금 규칙에 정의 된 패턴과 여기에서 크롤링을 시작 치료에서 CrawlSpider 초기화하기

  • 의 URL http://www.example.de/index/search?filter=homepage
  • 로 진행

    • 크롤 시작 URL http://www.example.de/index/search?method=simple

    기본적으로 변경해야하는 것은 그 사이에 하나의 URL을 호출하는 것입니다. BaseSpider로 모든 것을 다시 쓰지 않으려 고합니다. 그래서 누군가가 이것을 성취하는 방법에 대한 아이디어를 가지고 있기를 바랍니다. :)

    추가 정보가 필요하면 알려주십시오. 아래에서 현재 스크립트를 찾을 수 있습니다.

    #!/usr/bin/python 
    # -*- coding: utf-8 -*- 
    
    from scrapy.contrib.spiders import CrawlSpider, Rule 
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 
    from scrapy.selector import HtmlXPathSelector 
    from scrapy.http import Request 
    from example.items import ExampleItem 
    from scrapy.contrib.loader.processor import TakeFirst 
    import re 
    import urllib 
    
    take_first = TakeFirst() 
    
    class ExampleSpider(CrawlSpider): 
        name = "example" 
        allowed_domains = ["example.de"] 
    
        start_url = "http://www.example.de/index/search?method=simple" 
        start_urls = [start_url] 
    
        rules = (
         # http://www.example.de/index/search?page=2 
         # http://www.example.de/index/search?page=1&tab=direct 
         Rule(SgmlLinkExtractor(allow=('\/index\/search\?page=\d*$',)), callback='parse_item', follow=True), 
         Rule(SgmlLinkExtractor(allow=('\/index\/search\?page=\d*&tab=direct',)), callback='parse_item', follow=True), 
        ) 
    
        def parse_item(self, response): 
         hxs = HtmlXPathSelector(response) 
    
         # fetch all company entries 
         companies = hxs.select("//ul[contains(@class, 'directresults')]/li[contains(@id, 'entry')]") 
         items = [] 
    
         for company in companies: 
          item = ExampleItem() 
          item['name'] = take_first(company.select(".//span[@class='fn']/text()").extract()) 
          item['address'] = company.select(".//p[@class='data track']/text()").extract() 
          item['website'] = take_first(company.select(".//p[@class='customurl track']/a/@href").extract()) 
    
          # we try to fetch the number directly from the page (only works for premium entries) 
          item['telephone'] = take_first(company.select(".//p[@class='numericdata track']/a/text()").extract()) 
    
          if not item['telephone']: 
           # if we cannot fetch the number it has been encoded on the client and hidden in the rel="" 
           item['telephone'] = take_first(company.select(".//p[@class='numericdata track']/a/@rel").extract()) 
    
          items.append(item) 
         return items 
    

    편집 여기

    InitSpider 내 시도 : https://gist.github.com/150b30eaa97e0518673a 여기에서 그런 생각 가지고 : Crawling with an authenticated session in Scrapy

    당신은 여전히 ​​CrawlSpider에서 상속 볼 수 있듯이,하지만 내가 만든이 핵심 Scrapy 파일에 대한 일부 변경 사항 (필자가 선호하는 방식이 아님). CrawlSpider는 BaseSpider (source) 대신 InitSpider를 상속받습니다.

    이것은 지금까지는 작동하지만 스파이더는 다른 페이지를 모두 차지하는 대신 첫 번째 페이지에서 멈 춥니 다.

    또한,이 방법은 자신을

    답변

    2

    좋아, 나는 해결책을 찾았 나 : 절대적으로 불필요한 것으로 보인다과 실제로 내가 처음 : 여기

    는 단순화 된 스크립트입니다 생각했던 것보다 훨씬 간단합니다 :

    #!/usr/bin/python 
    # -*- coding: utf-8 -*- 
    
    from scrapy.spider import BaseSpider 
    from scrapy.http import Request 
    from scrapy import log 
    from scrapy.selector import HtmlXPathSelector 
    from example.items import ExampleItem 
    from scrapy.contrib.loader.processor import TakeFirst 
    import re 
    import urllib 
    
    take_first = TakeFirst() 
    
    class ExampleSpider(BaseSpider): 
        name = "ExampleNew" 
        allowed_domains = ["www.example.de"] 
    
        start_page = "http://www.example.de/index/search?method=simple" 
        direct_page = "http://www.example.de/index/search?page=1&tab=direct" 
        filter_page = "http://www.example.de/index/search?filter=homepage" 
    
        def start_requests(self): 
         """This function is called before crawling starts.""" 
         return [Request(url=self.start_page, callback=self.request_direct_tab)] 
    
        def request_direct_tab(self, response): 
         return [Request(url=self.direct_page, callback=self.request_filter)] 
    
        def request_filter(self, response): 
         return [Request(url=self.filter_page, callback=self.parse_item)] 
    
        def parse_item(self, response): 
         hxs = HtmlXPathSelector(response) 
    
         # fetch the items you need and yield them like this: 
         # yield item 
    
         # fetch the next pages to scrape 
         for url in hxs.select("//div[@class='limiter']/a/@href").extract(): 
          absolute_url = "http://www.example.de" + url    
          yield Request(absolute_url, callback=self.parse_item) 
    

    이제 보았 듯이 BaseSpider를 사용하고 끝에 새로운 Requests를 생성합니다. 그리고 처음에는 크롤링을 시작하기 전에 필요한 다양한 요청을 처리합니다.

    누군가에게 도움이되기를 바랍니다. 질문이 있으시면 기꺼이 답변 해 드리겠습니다.

    관련 문제