scrapy简单学习

学习网站:scrapy入门教程

1.创建项目:cmd打开scrapy所在位置,输入命令

scrapy startproject tutorial

2.定义item:编辑item.py,对您想要采集的数据类型进行定义。例如:

import scrapy

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

3.编写爬虫:在spiders的文件下新建一个domz_spider.py文件,代码如下:

import scrapy

from tutorial.items import DmozItem

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):
        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

4.启动爬虫:在cmd的命令行转至spiders的根目录下,输入命令

scrapy crawl dmoz     

5.保存数据:

scrapy crawl dmoz -o items.json

或者

scrapy crawl dmoz -o items.csv

你可能感兴趣的:(pythonscrapy)