16

I am using scrapy to crawl old sites that I own, I am using the code below as my spider. I don't mind having files outputted for each webpage, or a database with all the content within that. But I do need to be able to have the spider crawl the whole thing with out me having to put in every single url that I am currently having to do

import scrapy

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["www.example.com"]
    start_urls = [
        "http://www.example.com/contactus"
    ]

    def parse(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)

1 Answer 1

26

To crawl whole site you should use the CrawlSpider instead of the scrapy.Spider

Here's an example

For your purposes try using something like this:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

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

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)

Also, take a look at this article

7
  • 1
    You probably want to add follow=True to that rule, to continue crawling links. Apr 25, 2016 at 13:06
  • @Daniil Mashkin, your solution also helped me, thanks for that, but now i wonder what does the [-2] is for? thanks in advance. How can i save all my scraped links into a .csv file? if i run"scrapy crawl spider -o .example.csv" i get an empty .csv file :/
    – y.y
    Aug 4, 2020 at 6:56
  • @y.y you should have your own Item class with url field and just return it in the parse_item method. Then your scrapy crawl spider -o .example.csv will work fine
    – Danil
    Aug 4, 2020 at 9:33
  • or try return {'url': response.url}
    – Danil
    Aug 4, 2020 at 9:35
  • @Daniil Mashkin i can confirm that, thanks. do you know how i can check all my scraped links, which are stored in a csv file, for productlinks and maybe some categorylinks? that i got in the end one csv with productfiles and one with categorylinks
    – y.y
    Aug 4, 2020 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.