scrapy — кроулим, парсим и грабим

scrapy — весьма ценная библиотека для тех, кому нужно пройти по большому массиву страниц (с большой вложенностью, заранее не ограниченному), и добыть оттуда набор однотипной информации.

В общем, пойди туда — пока не знаю куда, принеси то — пока не знаю что. И сформируй из этого таблицу csv или файл json.

pip install scrapy
# создаем новый проект - ScrapySample
scrapy startproject ScrapySample

Редактируем конфигурационные файлы. Сначала что собирать — файл item.py в папке webcrawl

from scrapy.item import Item, Field
class ScrapySample(Item):
    title = Field()
    link = Field() 
    content = Field() 
    pass

Теперь сам паук. В папкe ScrapySample/spiders создаем ScrapySpider.py

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http.request import Request
from scrapy_sample.items import ScrapySampleItem

class ScrapyOrgSpider(BaseSpider):
    name = "scrapy"
    allowed_domains = ["scrapy.org"]
    start_urls = ["http://blog.scrapy.org/"]

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

        next_page = hxs.select("//div[@class='pagination']/a[@class='next_page']/@href").extract()
        if next_page:
            yield Request(next_page[0], self.parse)

        posts = hxs.select("//div[@class='post']")
        items = []
        for post in posts:
            item = ScrapySampleItem()
            item["title"] = post.select("div[@class='bodytext']/h2/a/text()").extract()
            item["link"] = post.select("div[@class='bodytext']/h2/a/@href").extract()
            item["content"] = post.select("div[@class='bodytext']/p/text()").extract()
            items.append(item)
        for item in items:
            yield item
            # возвращаем генератор собранных объектов

Запускаем:

scrapy crawl ScrapySample -o ScrapySample.json -t json

(можно в csv или xml)

Thanks :

http://amaral.northwestern.edu/blogs/2013/apr/8/quick-introduction-web-crawling-using-scrapy-part-/

https://github.com/milinda/Scrapy-Sample/blob/0a8ffba73f5f31b2a37d87530ceb341e7302182d/scrapy_sample/spiders/ScrapySpider.py