Python爬虫学习笔记
  • Introduction
  • 爬虫简介
    • 1.1 了解网页结构
  • BeautifulSoup 解析网页
    • 2.1 BeautifulSoup 解析网页: 基础
    • 2.2 BeautifulSoup 解析网页: CSS
    • 2.3 BeautifulSoup 解析网页: 正则表达
    • 2.4 小练习: 爬百度百科
  • 更多请求/下载方式
    • 3.1 多功能的 Requests
    • 3.2 下载文件
    • 3.3 小练习: 下载美图
  • 加速你的爬虫
    • 4.1 加速爬虫: 多进程分布式
    • 4.2 加速爬虫: 异步加载 Asyncio
  • 高级爬虫
    • 5.1 高级爬虫: 让 Selenium 控制你的浏览器帮你爬
    • 5.2 高级爬虫: 高效无忧的 Scrapy 爬虫库
Powered by GitBook
On this page

Was this helpful?

  1. 高级爬虫

5.2 高级爬虫: 高效无忧的 Scrapy 爬虫库

Previous5.1 高级爬虫: 让 Selenium 控制你的浏览器帮你爬

Last updated 6 years ago

Was this helpful?

Scrapy 是一个整合了的爬虫框架, 有着非常健全的管理系统. 也是分布

式爬虫

一定还要给这个 spider 一个名字,给定一些初始爬取的网页, 写在start_urls 里,在 scrapy 中它自动帮你去重

import scrapy

class MofanSpider(scrapy.Spider):
    name = "mofan"
    start_urls = [
        'https://morvanzhou.github.io/',
    ]
    # unseen = set()
    # seen = set()      # 我们不在需要 set 了, 它自动去重
    def parse(self, response):
        yield {     # return some results
            'title': response.css('h1::text').extract_first(default='Missing').strip().replace('"', ""),
            'url': response.url,
        }

        urls = response.css('a::attr(href)').re(r'^/.+?/$')     # find all sub urls
        for url in urls:
            yield response.follow(url, callback=self.parse)     # it will filter duplication automatically

不需要使用 urljoin(),在 follow() 这一步会自动检测 url 的格式

$ scrapy runspider 5-2-scrapy.py -o res.json -s FEED_EXPORT_ENCODING=utf-8

-o res.json 这个 -o 就是输出的指令, 可以在那个文件夹中找到一个名字叫 res.json 的文件, 里面存有所有找到的 {title:, url:}.