[爬虫] 学Scrapy,顺便把它的官方教程给爬下来

想学爬虫主要是因为算法和数据是密切相关的,有数据之后可以玩更多有意思的事情,数据量大可以挖掘挖掘到更多的信息。

之前只会通过python中的request库来下载网页内容,再用BeautifulSoup、re正则工具来解析;后来了解到Scrapy爬虫框架,现在入门先写个小小的爬虫项目,这里做个简单的总结和记录。

 

官方教程:https://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/overview.html(包括安装指南)

Github:https://github.com/scrapy

 

1. 创建项目

scrapy startproject -h
scrapy startproject scrapytutorial
cd scrapytutorial/
scrapy genspider scrapy_tutorial_spider scrapy-chs.readthedocs.io
mkdir output

 

2. 编写爬虫代码

# -*- coding: utf-8 -*-
import scrapy
import codecs


class ScrapyTutorialSpiderSpider(scrapy.Spider):
    name = 'scrapy_tutorial_spider'
    # allowed_domains = ['scrapy-chs.readthedocs.io']
    start_urls = ['https://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/overview.html']

    def parse(self, response):
        print("response.url: %s" % response.url)

        # 保存完整网页内容到文件
        filename = response.url.split("/")[-1]
        print("filename: %s" % filename)
        with codecs.open("output/" + filename, "wb") as fw:
            fw.write(response.body)

        # TODO 提取关键信息

        # 遍历下一页
        next_url = response.css("div.rst-footer-buttons > a::attr('href')").extract()[0]
        if next_url is not None:
            next_url = response.urljoin(next_url)
            print("next_url: %s" % next_url)
            yield scrapy.Request(next_url)

 

3. 启动爬取

scrapy crawl scrapy_tutorial_spider

 完整爬下来有45个文件:

 

因为刚上手,先按下面几步走:

(1) 把某个网页完整爬下来,保存到文件
(2) 追踪链接:通过提取感兴趣的页面的链接(例如想要下一页的内容)并进行追踪,获取更多的数据
(3) 动态解析网页,只提取感兴趣的部分内容并保存

 

目前还不太熟悉CSS选择器以及XPath表达式,关于第(3)部提取关键信息还没做,后续将会逐渐学习和完善。

(参考官网的两个例子:tutorialQuotesBot

 

另外,网上有很多不错的爬虫项目,可以用来练手:32个Python爬虫项目

爬虫可能涉及到定时爬取、账号注册和登录、验证码破解等等,还是挺有挑战性的~

posted @ 2018-07-26 18:41  焦距  阅读(287)  评论(0编辑  收藏  举报