Adders Adders - 6 months ago 23
Python Question

Defining Additional Methods in a Scrapy Class

How is a Scrapy class executed and how do you include additional methods to a spider class?

For example, from the docs:

import scrapy

class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]

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


If I wanted to define some methods for polling a database or something else, how might I go about that, and why?

Answer

Let's take a look on the following use case - getting the urls to crawl from a database. For this, instead of start_urls, you need to use start_requests() method.

Sample code (using MySQLdb driver directly):

import MySQLdb
import scrapy

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]

    def start_requests(self):
        db = MySQLdb.connect(host="host", user="user" ...) 
        cursor = db.cursor()

        cursor.execute("SELECT url from url_table")
        requests = [scrapy.Request(url=row[0]) for row in cursor.fetchall()]

        cursor.close()

        return requests

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