1

我对scrapy很陌生,而且我以前没有使用过正则表达式

以下是我的spider.py代码

class ExampleSpider(BaseSpider):
   name = "test_code
   allowed_domains = ["www.example.com"]
   start_urls = [
       "http://www.example.com/bookstore/new/1?filter=bookstore",
       "http://www.example.com/bookstore/new/2?filter=bookstore",
       "http://www.example.com/bookstore/new/3?filter=bookstore",
   ]

   def parse(self, response):
       hxs = HtmlXPathSelector(response)

现在,如果我们查看start_urls所有三个 url 都是相同的,除了它们在整数值上有所不同,2?, 3?依此类推,我的意思是根据网站上存在的 url 不受限制,现在我们可以使用 crawlspider,我们可以为 URL 构造正则表达式,如下所示,

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

    class ExampleSpider(CrawlSpider):
        name = 'example.com'
        allowed_domains = ['example.com']
        start_urls = [
       "http://www.example.com/bookstore/new/1?filter=bookstore",
       "http://www.example.com/bookstore/new/2?filter=bookstore",
       "http://www.example.com/bookstore/new/3?filter=bookstore",
   ]

        rules = (
            Rule(SgmlLinkExtractor(allow=(........),))),
        ) 

   def parse(self, response):
       hxs = HtmlXPathSelector(response)

start_url你能指导我吗,我怎样才能为上面的列表构建一个爬虫规则。

4

2 回答 2

4

如果我理解正确,您需要大量具有特定模式的起始 URL。

如果是这样,您可以覆盖BaseSpider.start_requests方法:

class ExampleSpider(BaseSpider):
    name = "test_code"
    allowed_domains = ["www.example.com"]

    def start_requests(self):
        for i in xrange(1000):
            yield self.make_requests_from_url("http://www.example.com/bookstore/new/%d?filter=bookstore" % i)

    ...
于 2012-05-24T18:02:02.297 回答
0

如果您使用的是 CrawlSpider,覆盖 parse 方法通常不是一个好主意。

规则对象可以将您感兴趣的网址过滤到您不关心的网址。

请参阅文档中的CrawlSpider以供参考。

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

class ExampleSpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com/bookstore']

    rules = (
        Rule(SgmlLinkExtractor(allow=('\/new\/[0-9]\?',)), callback='parse_bookstore'),
    )

def parse_boostore(self, response):
   hxs = HtmlXPathSelector(response)
于 2012-05-24T17:27:14.713 回答