11
votes

I'm unable to crawl a whole website, Scrapy just crawls at the surface, I want to crawl deeper. Been googling for the last 5-6 hours and no help. My code below:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from scrapy.spider import BaseSpider
from scrapy import log

class ExampleSpider(CrawlSpider):
    name = "example.com"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/"]
    rules = [Rule(SgmlLinkExtractor(allow=()), 
                  follow=True),
             Rule(SgmlLinkExtractor(allow=()), callback='parse_item')
    ]
    def parse_item(self,response):
        self.log('A response from %s just arrived!' % response.url)
2
Just tried your code against stackoverflow - my ip got banned. It definitely works! :)alecxe
@Alexander - Sounds encouraging for me to debug more :) :) ... Sorry on the IP ban mate !Abhiram Sampath
Are you really trying to crawl example.com? You know that's not a real website.Steven Almeroth
Which website are you trying to crawl?Talvalin
"example.com" was used for representative purposes only. I'm trying to crawl landmarkshops.comAbhiram Sampath

2 Answers

6
votes

Rules short-circuit, meaning that the first rule a link satisfies will be the rule that gets applied, your second Rule (with callback) will not be called.

Change your rules to this:

rules = [Rule(SgmlLinkExtractor(), callback='parse_item', follow=True)]
2
votes

When parsing the start_urls, deeper urls can be parsed by the tag href. Then, deeper request can be yielded in the function parse(). Here is a simple example. The most important source code is shown below:

from scrapy.spiders import Spider
from tutsplus.items import TutsplusItem
from scrapy.http    import Request
import re

class MySpider(Spider):
    name            = "tutsplus"
    allowed_domains = ["code.tutsplus.com"]
    start_urls      = ["http://code.tutsplus.com/"]

    def parse(self, response):
        links = response.xpath('//a/@href').extract()

        # We stored already crawled links in this list
        crawledLinks = []

        # Pattern to check proper link
        # I only want to get tutorial posts
        linkPattern = re.compile("^\/tutorials\?page=\d+")

        for link in links:
        # If it is a proper link and is not checked yet, yield it to the Spider
            if linkPattern.match(link) and not link in crawledLinks:
                link = "http://code.tutsplus.com" + link
                crawledLinks.append(link)
                yield Request(link, self.parse)

        titles = response.xpath('//a[contains(@class, "posts__post-title")]/h1/text()').extract()
        for title in titles:
            item = TutsplusItem()
            item["title"] = title
            yield item