利用scrapy框架实现一个简单的爬虫项目

首先简单介绍一下什么是scrapy框架?具体详情见百科!!!

总之,scrapy是一个用于python开发抓取网站网页的框架,更加通俗的讲就是爬虫框架!!!

下面就是利用scrapy爬取web的一个小项目:

爬取的网站:http://books.toscrape.com

import scrapy

class BooksSpider(scrapy.Spider):
    name = 'books'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):

        # 1.提取数据
        for sel in response.css('article.product_pod'):
            #获取书名
            name  = sel.xpath('//h3/a[@title]/text()').extract_first()
            #获取书的价格
            price = sel.css(' p.price_color::text').extract_first()
            #获取书的评分  这里使用到正则匹配标签属性中的评分
            rating = sel.css('p.star-rating').re_first('star-rating (\w+)')

            #把属性封装入字典中
            book = {
                'name':name,
                'price':price,
                'rating':rating,
            }

            yield book

        # 2.提取链接,产生新的请求
        #提取下一页的链接
        next_page = response.css('ul.pager li.next a::attr(href)').extract_first()

        #判断下一页是否存在
        if next_page:
            """
            这里注意urljoin()函数的用法,从相对路径获得绝对路径
            from urlparse import urljoin
           输入: urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
           输出:'http://www.asite.com/folder/anotherpage.html'
            """
            next_page = response.urljoin(next_page)
            request = scrapy.Request(next_page,callback=self.parse)
            yield request

注意:

1.在终端运行时,输入scrapy crawl books -o books.csv 运行会把获取的结果保存在books.csv文件中。

2.其中使用到了urljoin函数的用法。

3.yield的用法。

猜你喜欢

转载自blog.csdn.net/cai_cai_cai_1992/article/details/82960788