- 众所周知scrapy框架具有高效率和高自由度的特点,但是较高的封装度,在实现一些小功能的时候会比较麻烦
- 12306抢票脚本项目在Github上并不算少,尤其是那个28k收藏的大佬项目,但是大佬的代码比较异于常人,许多模块都是自己封装的,而使用scrapy做的人比较少,而且除了大佬的项目其他人的基本用不了(大佬的有时也不行),于是想自己做这个脚本
- 12306抢票思路很简单:1.查询余票(无需登录)2.登录 3.抢票
- 查询余票的数据并不在查票页面的源代码里(https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=百色,BIZ&ts=南宁,NNZ&date=2020-06-02&flag=N,N,Y),而是采用Ajax加载的方式放在(https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2020-06-02&leftTicketDTO.from_station=BIZ&leftTicketDTO.to_station=NNZ&purpose_codes=ADULT)
- 我们的目标就是get方式请求第二个页面,返回并分析
- 所以复写start_requests()和几个get请求中cookie的传递是重点,以下是各部分代码
Spider.py
# -*- coding: utf-8 -*-
import scrapy
import requests
import json
from ticket.items import TicketItem
from selenium import webdriver
class A12306SpiderSpider(scrapy.Spider):
name = '12306_spider'
allowed_domains = ['12306.cn']
start_urls = [
'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=%E5%8D%97%E5%AE%81,NNZ&ts=%E7%99%BE%E8%89%B2,BIZ&date=2020-06-02&flag=N,N,Y','https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2020-06-02&leftTicketDTO.from_station=NNZ&leftTicketDTO.to_station=BIZ&purpose_codes=ADULT']
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.37'}
def start_requests(self):
url='https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=%E7%99%BE%E8%89%B2,BIZ&ts=%E5%8D%97%E5%AE%81,NNZ&date=2020-06-02&flag=N,N,Y'
req=scrapy.Request(url=url,headers=self.headers,callback=self.get_cookie,meta={'cookiejar':1})
yield req
def get_cookie(self, response):
url='https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2020-06-02&leftTicketDTO.from_station=BIZ&leftTicketDTO.to_station=NNZ&purpose_codes=ADULT'
req=scrapy.Request(url=url,meta={'cookiejar':response.meta['cookiejar']},headers=self.headers,callback=self.get_train_info)
yield req
def get_train_info(self,response):
text =response.body.decode('UTF-8')
text=json.loads(text)
result = text['data']['result']
print(result)
for i in result:
item = i.split('|')
train_code = item[3]
train_start_time = item[8]
train_end_time = item[9]
sit_1 = item[31]
sit_2 = item[30]
items = TicketItem(train_code=train_code, train_start_time=train_start_time, train_end_time=train_end_time,
sit_1=sit_1, sit_2=sit_2)
yield items
pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import random
from scrapy.exporters import JsonLinesItemExporter,JsonItemExporter,CsvItemExporter
class TicketPipeline:
def __init__(self):
self.fp=open('ticket.json','wb')
self.exporter=JsonLinesItemExporter(self.fp,ensure_ascii=False)
def start_spider(self):
self.exporter.start_exporting()
def process_item(self, item, spider):
self.exporter.export_item(item)
def close_item(self):
self.fp.close()
- 储存器中间件用的是json数据格式保存数据
settings.py
# -*- coding: utf-8 -*-
# Scrapy settings for ticket project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'ticket'
SPIDER_MODULES = ['ticket.spiders']
NEWSPIDER_MODULE = 'ticket.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'ticket (+http://www.yourdomain.com)'
from fake_useragent import UserAgent
import random
# 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://docs.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 = True
# 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',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.37'
}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'ticket.middlewares.TicketSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'ticket.middlewares.TicketDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'ticket.pipelines.TicketPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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://docs.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'
setting只要注意header的设置就行