Scrapy at a glance

Scrapy Tutorial Learning Notes

Scrapy is an application framework for crawling web sites and extracting structured data which can be used for a wide range of useful applications, like data mining, information processing or historical archival.

Even though Scrapy was originally designed for web scraping, it can also be used to extract data using APIs (such as Amazon Associates Web Services) or as a general purpose web crawler.

Install Scrapy in Ubuntu

sudo apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev
pip install Scrapy

Creating a project

scrapy startproject tutorial

project directory

tutorial/
scrapy.cfg            # deploy configuration file

tutorial/             # project's Python module, you'll import your code from here
    __init__.py

    items.py          # project items file

    pipelines.py      # project pipelines file

    settings.py       # project settings file

    spiders/          # a directory where you'll later put your spiders
        __init__.py
        ...

Defining our Item

Items are containers that will be loaded with the scraped data, they are declared by creating a scrapy.Item class and defining its attributes as scrapy.Field objects.

import scrapy

class DmozItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    desc = scrapy.Field()

Spider

Spiders are classes that you define and Scrapy uses to scrape information from a domain (or group of domains).

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)

To create a Spider, you must subclass scrapy.Spider and define some attributes:

  • name: identifies the Spider. It must be unique.
  • start_urls: a list of URLs where the Spider will begin to crawl from.
  • parse(): a method of the spider, which will be called with the downloaded Response object of each start URL. The response is passed to the method as the first and only argument.This method is responsible for parsing the response data and extracting scraped data (as scraped items) and more URLs to follow(as Request objects).

Crawling

scrapy crawl dmoz

Scrapy creates scrapy.Request objects for each URL in the start_urls attribute of the Spider, and assigns them the parse method of the spider as their callback function.

These Requests are scheduled, then executed, and scrapy.http.Response objects are returned and then fed back to the spider, through the parse() method.

Extracting the Data

Scrapy uses a mechanism based on XPath or CSS expressions called Scrapy Selectors to extract data from web pages.You can see selectors as objects that represent nodes in the document structure.

Selectors have four basic methods:

  • xpath(): returns a list of selectors, each of which represents the nodes selected by the xpath expression given as argument.
  • css(): returns a list of selectors, each of which represents the nodes selected by the CSS expression given as argument.
  • extract(): returns a unicode string with the selected data.
  • re(): returns a list of unicode strings extracted by applying the regular expression given as argument.

scrapy.http.Response objects has a selector attribute which is an instance of Selector class. You can run queries on response by calling response.selector.xpath() or response.selector.css()or response.xpath() or response.css() for short.

Using our Item

Item objects are custom Python dicts; you can access the values of their fields using the standard dict syntax like:

def parse(self, response):
    for sel in response.xpath('//ul/li'):
        item = DmozItem()
        item['title'] = sel.xpath('a/text()').extract()
        item['link'] = sel.xpath('a/@href').extract()
        item['desc'] = sel.xpath('text()').extract()
        yield item

Following links

extract the links for the pages you are interested, follow them and then extract the data you want for all of them.

def parse(self, response):
    for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
        url = response.urljoin(href.extract())
        yield scrapy.Request(url, callback=self.parse_articles_follow_next_page)

def parse_articles_follow_next_page(self, response):
for article in response.xpath("http://article"):
    item = ArticleItem()

    ... extract article data here

    yield item

next_page = response.css("ul.navigation > li.next-page > a::attr('href')")
if next_page:
    url = response.urljoin(next_page[0].extract())
    yield scrapy.Request(url, self.parse_articles_follow_next_page)

When you yield a Request in a callback method, Scrapy will schedule that request to be sent and register a callback method to be executed when that request finishes.

Storing the scraped data

scrapy crawl dmoz -o items.json

That will generate an items.json file containing all scraped items, serialized in JSON.If you want to perform more complex things with the scraped items, you can write an Item Pipeline.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子赴邻,更是在濱河造成了極大的恐慌调炬,老刑警劉巖迷雪,帶你破解...
    沈念sama閱讀 206,013評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)绅你,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,205評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來昭躺,“玉大人忌锯,你說我怎么就攤上這事×祆牛” “怎么了汉规?”我有些...
    開封第一講書人閱讀 152,370評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我针史,道長,這世上最難降的妖魔是什么碟狞? 我笑而不...
    開封第一講書人閱讀 55,168評(píng)論 1 278
  • 正文 為了忘掉前任啄枕,我火速辦了婚禮,結(jié)果婚禮上族沃,老公的妹妹穿的比我還像新娘频祝。我一直安慰自己,他們只是感情好脆淹,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,153評(píng)論 5 371
  • 文/花漫 我一把揭開白布常空。 她就那樣靜靜地躺著,像睡著了一般盖溺。 火紅的嫁衣襯著肌膚如雪漓糙。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 48,954評(píng)論 1 283
  • 那天烘嘱,我揣著相機(jī)與錄音昆禽,去河邊找鬼。 笑死蝇庭,一個(gè)胖子當(dāng)著我的面吹牛醉鳖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播哮内,決...
    沈念sama閱讀 38,271評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼盗棵,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了北发?” 一聲冷哼從身側(cè)響起纹因,我...
    開封第一講書人閱讀 36,916評(píng)論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鲫竞,沒想到半個(gè)月后辐怕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,382評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡从绘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,877評(píng)論 2 323
  • 正文 我和宋清朗相戀三年寄疏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片僵井。...
    茶點(diǎn)故事閱讀 37,989評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡陕截,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出批什,到底是詐尸還是另有隱情农曲,我是刑警寧澤,帶...
    沈念sama閱讀 33,624評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站乳规,受9級(jí)特大地震影響形葬,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜暮的,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,209評(píng)論 3 307
  • 文/蒙蒙 一笙以、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧冻辩,春花似錦猖腕、人聲如沸恨闪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,199評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咙咽。三九已至老玛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間犁珠,已是汗流浹背逻炊。 一陣腳步聲響...
    開封第一講書人閱讀 31,418評(píng)論 1 260
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留犁享,地道東北人余素。 一個(gè)月前我還...
    沈念sama閱讀 45,401評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像炊昆,于是被迫代替她去往敵國和親桨吊。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,700評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容