1

Rule SgmlLinkExtractor の書き方を教えてください
混乱していて、英語のドキュメントがわかりません

多くのページで Web をクロールしたいのですが
、ルールは次のとおりです。

 http://abctest.com/list.php?c=&&page=1  
 http://abctest.com/list.php?c=&&page=2  
 http://abctest.com/list.php?c=&&page=3 ...

これが私のコードです:

from scrapy.selector import Selector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
import re

class Spider(CrawlSpider):
    name = "find"
    start_urls = ["http://abctest.com/list.php?c=&&page=1",]
    #crawl 2 pages to test if the data is normal  allow=('?c=&&page=/d+')
    rules = [Rule(SgmlLinkExtractor(allow=('?c=&&page=2')),callback='parse_item',follow=True)]


    #get the page1 item
    def parse(self, response):
        sel = Selector(response)
        sites = sel.css("div#list table tr ")
        for site in sites:
            item = LAItem()
            item['day']  = site.css("  td.date::text ").extract()
            item['URL'] = site.css("  td.subject a::attr(href) ").extract()
         yield item

   #get the page2 item    
   def parse_item(self, response):
        sel = Selector(response)
        sites = sel.css("div#list table tr ")
        for site in sites:
            item = LAItem()
            item['day']  = site.css("  td.date::text ").extract()
            item['URL'] = site.css("  td.subject a::attr(href) ").extract()
         yield item   
4

1 に答える 1

1

LinkExtractorここでandは本当に必要ありませんCrawlSpider- ただ通常のSpider. 必要なのは、start_requests()メソッドを定義し、そこからリクエストを生成することです:

from scrapy import Request, Spider
from scrapy.exceptions import CloseSpider
from scrapy.selector import Selector

URL = 'http://abctest.com/list.php?c=&&page={page}'


class Spider(Spider):
    handle_httpstatus_list = [404]
    name = "find"

    def start_requests(self):
        index = 1
        while True:
            yield Request(URL.format(page=index))
            index +=1

    def parse(self, response):
        if response.status == 404:
            raise CloseSpider("Met the page which doesn't exist")

        sel = Selector(response)
        sites = sel.css("div#list table tr ")
        for site in sites:
            item = LAItem()
            item['day']  = site.css("  td.date::text ").extract()
            item['URL'] = site.css("  td.subject a::attr(href) ").extract()
         yield item

ここでの秘訣は、404 - ページが見つからないという最初の応答に遭遇するまでページを取得し続けることです。これにより、任意の数のページで機能するはずです。

于 2014-07-30T03:24:37.083 に答える