scrapy---简介 、(爬取赶集)

在这里插入图片描述
创建scrapy文件

C:\Users\dell\PycharmProjects\TestDemo001\TestDemo001>scrapy startproject TestDemo001

scrapy genspider -t basic ganji "http://anqing.ganji.com/"

scrapy crawl ganji

存储csv

scrapy crawl ganji -o ganji.csv

爬赶集
在这里插入图片描述
ganji.py

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

from TestDemo001.items import Testdemo001Item


class GanjiSpider(scrapy.Spider):
    name = 'ganji'
    allowed_domains = ['http://anqing.ganji.com/']
    start_urls = []
    start_url = 'http://bj.ganji.com/site/s/f0/_%E7%A8%8B%E5%BA%8F%E5%91%98/'
    for i in range(0,1985,32):
        start_urls.append(start_url.replace("f0","f"+str(i)))

    def parse(self, response):
        node_list = response.xpath("//div[@class='job-wanted']/dl")
        for node in node_list:
            try:
                ti = Testdemo001Item()
                name = node.xpath("./dt[@class='f-introd']/a/text()").extract()[0]
                addr = node.xpath("./dd[@class='addr']/a/text()").extract()[0]
                time = node.xpath("./dd[@class='j-time']/text()").extract()[0]
                ti["name"] = name
                ti["addr"] = addr
                ti["time"] = time
                yield ti
            except:
                pass

item.py

import scrapy


class Testdemo001Item(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    addr = scrapy.Field()
    time = scrapy.Field()

pipelines.py

class Testdemo001Pipeline(object):
    def process_item(self, item, spider):
       # with open("text.txt","w+") as f:
            #f.write(item)
        if item ==None:
            return None
        else:
            with open("text.txt","a+") as f:
                f.write(item["name"]+item["addr"]+item["time"]+"\n")
            return item

settings.py

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

# Scrapy settings for TestDemo001 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'TestDemo001'

SPIDER_MODULES = ['TestDemo001.spiders']
NEWSPIDER_MODULE = 'TestDemo001.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'TestDemo001 (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'TestDemo001.middlewares.Testdemo001SpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'TestDemo001.middlewares.Testdemo001DownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'TestDemo001.pipelines.Testdemo001Pipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是简单的步骤: 1. 安装 scrapyscrapy-redis ```python pip install scrapy scrapy-redis ``` 2. 创建一个 Scrapy 项目 ```python scrapy startproject douban_top250 ``` 3. 在 settings.py 中加入 scrapy-redis 的相关设置 ```python # 使用 scrapy-redis 的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 使用 scrapy-redis 的去重过滤器 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 允许暂停、恢复虫 SCHEDULER_PERSIST = True # 设置 redis 为 item pipeline ITEM_PIPELINES = { 'scrapy_redis.pipelines.RedisPipeline': 300 } # 设置 redis 服务器地址和端口号 REDIS_HOST = 'localhost' REDIS_PORT = 6379 ``` 4. 编写 spider ```python # coding:utf-8 import scrapy from scrapy import Request from scrapy_redis.spiders import RedisSpider class DoubanTop250Spider(RedisSpider): """爬取豆瓣电影 Top 250""" name = 'douban_top250' allowed_domains = ['movie.douban.com'] # 在 Redis 中设置起始爬取的 URL redis_key = 'douban:start_urls' def parse(self, response): # 获取电影列表 movie_list = response.css('.grid_view li') for movie in movie_list: # 获取电影名字和详情页 URL title = movie.css('.title::text').extract_first() detail_url = movie.css('.hd a::attr(href)').extract_first() yield Request(detail_url, callback=self.parse_detail, meta={'title': title}) # 获取下一页的链接 next_url = response.css('.next a::attr(href)').extract_first() if next_url: yield Request(next_url, callback=self.parse) def parse_detail(self, response): # 获取电影详情 title = response.meta['title'] score = response.css('.rating_num::text').extract_first() yield {'title': title, 'score': score} ``` 5. 运行 scrapy-redis 虫 首先要在终端中启动 redis 服务: ```python redis-server ``` 然后在一个终端中运行 scrapy-redis 虫: ```python scrapy runspider douban_top250.py ``` 在另一个终端中向 Redis 中添加起始 URL: ```python redis-cli lpush douban:start_urls https://movie.douban.com/top250 ``` 爬取结果会自动保存到 Redis 数据库中。你可以通过 redis-cli 或者其他 Redis 客户端查看结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值