Python_爬虫_基于Scrapy框架

使用Scrapy抓取一个网站共四(五)个步骤:

(1)创建一个Scrapy项目:在cmd中运行 scrapy startproject tutorial, tutorial 为项目名称
(2)定义Item容器:说明要爬取的内容,在 items.py中编写
(3)编写爬虫:在spiders文件夹中新建个py文件,并编写内容
(4)存储内容:在 pipelines.py 中编写
(5)配置爬虫:在setting.py中

1.创建一个Scrapy项目
(1)打开 cmd,转到桌面操作目录后,输入 scrapy startproject tutorial 来创建一个名为 tutorial 的项目(名为tutorial的文件夹);
在这里插入图片描述
(2)在该文件夹中的目录结构为:
在这里插入图片描述
第二层中“tutorial文件夹”:项目的大本营
第二层中“scrapy.cfg”:项目的配置文件
第三层中“spiders文件夹”:放置爬虫代码
第三层中“items.py”:定义项目中需要获取的字段
第三层中“middlewares.py”:项目中的中间件(自定义扩展下载功能的组件)
第三层中“pipelines.py”:定义项目中的存储方案
第三层中的“settings.py”:项目的设置文件

2.定义Item容器

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class TutorialItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    link = scrapy.Field()
    desc = scrapy.Field()

3.编写爬虫
爬取网站为dmoz(DMOZ网站是一个著名的开放式分类目录(Open DirectoryProject),之所以称为开放式分类目录,是因为DMOZ不同于一般分类目录网站利用内部工作人员进行编辑的模式,而是由来自世界各地的志愿者共同维护与建设的最大的全球目录社区)。该网站中的两个网页:
http://dmoztools.net/Computers/Programming/Languages/Python/Books/” “http://dmoztools.net/Computers/Programming/Languages/Python/Resources/
(1)编写爬虫类Spider(用户编写用于从网站上爬取数据的类),包含一个用于下载的初始URL、如何跟进网页中的链接、如何分析页面中的内容、提取生成item的方法。在“spiders文件夹”中创建“dmoz_spider.py”。

import scrapy

class DmozSpider(scrapy.Spider):
    name = "dmoz"  		#spider的名字
    allowed_domains = ['dmoztools.net']
    start_urls = [
                "http://dmoztools.net/Computers/Programming/Languages/Python/Books/"
                "http://dmoztools.net/Computers/Programming/Languages/Python/Resources/"
                ]

    def parse(self,response):       #解析返回的数据(response data),提取数据(生成item)
        filename = response.url.split("/")[-2]
        with open(filename, 'wb') as f:
            f.write(response.body)

(2)爬;在cmd中转到 tutorial 目录下,输入 scrapy crawl dmoz 就可以让爬虫爬起来。
在这里插入图片描述

(3)取;在Scrapy中使用一种基于XPath和CSS的表达机制:Scrapy Selectors(一种选择器,有四种基本方法)
— xpath(): 传入xpath 表达式,返回对应所有节点的 selector list 列表
— css(): 传入CSS表达式,返回对应所有节点的 selector list 列表
— extract(): 序列化该节点为Unicode 字符串并返回list
— re(): 根据传入的正则表达式对数据进行提取,返回Unicode 字符串 list 列表
可以通过“Scrapy Shell”测试代码,用 scrapy shell + “网址” 方式启动
在这里插入图片描述
Shell 载入后,获得 response 回应;输入 response.body 会看到 response 的 body 部分(抓取到的页面内容);输入 response.headers 查看网页的 header 信息。
在这里插入图片描述
在这里插入图片描述
使用XPath选择器查找网页中的信息, response.xpath() = response.selector.xpath() ; response.css() = response.selector.css() . (extract为提取)经过下边的测试最终确定为:

response.xpath('//title/text()')[0].extract()
或则 
response.xpath('//title/text()').extract_first()

在这里插入图片描述
根据网站上的审查元素,查找标签递进关系
在这里插入图片描述

获得标题:

response.xpath('//*[@id="site-list-content"]/div/div[3]/a/div/text()').extract()

获得网址:

 response.xpath('//*[@id="site-list-content"]/div/div[3]/a/@href').extract()

在这里插入图片描述
通过for循环获得标题:

sites = response.xpath('//*[@id="site-list-content"]/div')
        for site in sites:
            title = site.xpath('div[3]/a/div/text()').extract_first()
            print(title)

在这里插入图片描述
爬虫部分完整代码:

import scrapy
from tutorial.items import DmozItem


class DmozSpider(scrapy.Spider):
    name = "dmoz"        # spider的名字
    allowed_domains = ['dmoztools.net']
    start_urls = [
                "http://dmoztools.net/Computers/Programming/Languages/Python/Books/"
                "http://dmoztools.net/Computers/Programming/Languages/Python/Resources/"
                ]

    def parse(self, response):       # 解析返回的数据(response data),提取数据(生成item)
        items = []
        sel = scrapy.selector.Selector(response)
        sites = sel.xpath('//*[@id="site-list-content"]/div')
        # sites = response.xpath('//*[@id="site-list-content"]/div')
        for site in sites:
            item = DmozItem()
            item['title'] = site.xpath('div[3]/a/div/text()').extract_first()
            item['link'] = site.xpath('div[3]/a/@href').extract()
            item['desc'] = site.xpath('div[3]/div/text()').extract_first()
            items.append(item)
        return items

(4)存;通过cmd命令转到 tutorial 文件夹下,执行命令:

# 保存为json格式文档,文档名为 items.jion
scrapy crawl dmoz -o items.jion -t json
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值