너 바보 아니야

Python scrapy入门教程

2017-09-26

Python scrapy入门教程

Python 安装

Python下载地址:[ Python-Downloads ]

如果您已经熟悉 Python 包的安装,您可以从 PyPI 安装 Scrapy 及其依赖:

pip install Scrapy

win32api问题解决
安装pywin32地址:[ 安装pywin32 ]

No module named win32api问题解决

请确保下载与系统(win32或amd64)匹配的版本

引导完成以下任务

  • 创建一个新的 Scrapy 项目
  • 编写 爬虫 以抓取网站并提取数据
  • 使用命令行导出已爬取的数据
  • 将爬虫更改为递归跟进链接
  • 使用爬虫参数

在开始爬取之前,您必须设置一个新的Scrapy项目。进入您要存储代码的目录,并运行如下命令:

scrapy startproject tutorial

这将创建一个具有以下内容的 tutorial 目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
tutorial/
scrapy.cfg # 部署配置文件

tutorial/ # 项目的 Python 模块,您将从这里加入您的代码
__init__.py

items.py # 项目的 item 定义文件

pipelines.py # 项目的 pipelines 文件

settings.py # 项目的 settings 文件

spiders/ # 放置spider代码的目录.
__init__.py

我们的第一个爬虫

爬虫是您定义的类,Scrapy用它从网站(或一组网站)中抓取信息。它们必须子类化 scrapy.Spider 并定义初始请求,可选地如何跟踪页面中的链接,以及如何解析下载的页面内容以提取数据。

这是我们第一个爬虫的代码。将其保存在项目中的 tutorial / spiders 目录下名为 shunhua_spider.py 的文件中:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "shunhua"

    def start_requests(self):
        urls = [
            'https://shunhua.github.io/',
            'https://shunhua.github.io/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'shunhua-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

如何运行我们的爬虫

要让我们的蜘蛛工作,进入项目的根目录并运行:

scrapy crawl shunhua


  • Notice

如若需要,请戳 [ About ] 下联系我 欢迎联系.ok,enjoy it ! ~~

使用支付宝打赏
使用微信打赏

欢迎点击上方按钮对我打赏,谢谢你给我吃糖果