Python爬虫 --- Scrapy爬取IT桔子网

目标:

此次爬取主要是针对IT桔子网的事件信息模块,然后把爬取的数据存储到mysql数据库中。



目标分析:

通过浏览器浏览发现事件模块需要登录才能访问,因此我们需要先登录,抓取登录接口:


可以看到桔子网的登录接口是:https://www.itjuzi.com/api/authorizations,请求方式是post请求,数据的提交方式是payload,提交的数据格式是json(payload方式提交的数据一般都是json),再看一下响应:

发现没有响应数据,其实是有响应数据的,只是F12调试看不到,我们可以用postman来查看响应体:

可以发现响应体是json数据,我们先把它放到一边,我们再来分析事件模块,通过F12抓包调试发现事件模块的数据其实是一个ajax请求得到的:

ajax请求得到的是json数据,我们再看看headers:



可以发现headers里有一个Authorization参数,参数的值恰好是我们登录时登录接口返回的json数据的token部分,所以这个参数很有可能是判断我们是否登录的凭证,我们可以用postman模拟请求一下:

通过postman的模拟请求发现如我们所料,我们只要在请求头里加上这个参数我们就可以获得对应的数据了。
解决了如何获得数据的问题,再来分析一下如何翻页,通过对比第一页和第二页提交的json数据可以发现几个关键参数,page、pagetotal、per_page分别代表当前请求页、记录总数、每页显示条数,因此根据pagetotal和per_page我们可以算出总的页数,到此整个项目分析结束,可以开始写程序了。

scrapy代码的编写

1.创建scrapy项目和爬虫:

E:\>scrapy startproject ITjuzi
E:\>scrapy genspider juzi itjuzi.com

2.编写items.py:

# -*- 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 ItjuziItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    invse_des = scrapy.Field()
    invse_title = scrapy.Field()
    money = scrapy.Field()
    name = scrapy.Field()
    prov = scrapy.Field()
    round = scrapy.Field()
    invse_time = scrapy.Field()
    city = scrapy.Field()
    com_registered_name = scrapy.Field()
    com_scope = scrapy.Field()
    invse_company = scrapy.Field()

3.编写Spider:

import scrapy
from itjuzi.settings import JUZI_PWD, JUZI_USER
import json


class JuziSpider(scrapy.Spider):
    name = 'juzi'
    allowed_domains = ['itjuzi.com']

    def start_requests(self):
        """
        先登录桔子网
        """
        url = "https://www.itjuzi.com/api/authorizations"
        payload = {"account": JUZI_USER, "password": JUZI_PWD}
        # 提交json数据不能用scrapy.FormRequest,需要使用scrapy.Request,然后需要method、headers参数
        yield scrapy.Request(url=url,
                             method="POST",
                             body=json.dumps(payload),
                             headers={'Content-Type': 'application/json'},
                             callback=self.parse
                             )

    def parse(self, response):
        # 获取Authorization参数的值
        token = json.loads(response.text)
        url = "https://www.itjuzi.com/api/investevents"
        payload = {
                    "pagetotal": 0, "total": 0, "per_page": 20, "page": 1, "type": 1, "scope": "", "sub_scope": "",
                    "round": [], "valuation": [], "valuations": "", "ipo_platform": "", "equity_ratio": [""],
                    "status": "", "prov": "", "city": [], "time": [], "selected": "", "location": "", "currency": [],
                    "keyword": ""
                }
        yield scrapy.Request(url=url,
                             method="POST",
                             body=json.dumps(payload),
                             meta={'token': token},
                             # 把Authorization参数放到headers中
                             headers={'Content-Type': 'application/json', 'Authorization': token['data']['token']},
                             callback=self.parse_info
                             )
    def parse_info(self, response):
        # 获取传递的Authorization参数的值
        token = response.meta["token"]
        # 获取总记录数
        total = json.loads(response.text)["data"]["page"]["total"]
        # 因为每页20条数据,所以可以算出一共有多少页
        if type(int(total)/20) is not int:
            page = int(int(total)/20)+1
        else:
            page = int(total)/20

        url = "https://www.itjuzi.com/api/investevents"
        for i in range(1,page+1):
            payload = {
                "pagetotal": total, "total": 0, "per_page": 20, "page":i  , "type": 1, "scope": "", "sub_scope": "",
                "round": [], "valuation": [], "valuations": "", "ipo_platform": "", "equity_ratio": [""],
                "status": "", "prov": "", "city": [], "time": [], "selected": "", "location": "", "currency": [],
                "keyword": ""
            }
            yield scrapy.Request(url=url,
                                 method="POST",
                                 body=json.dumps(payload),
                                 headers={'Content-Type': 'application/json', 'Authorization': token['data']['token']},
                                 callback=self.parse_detail
                                 )
       

    def parse_detail(self, response):
        infos = json.loads(response.text)["data"]["data"]      
        for i in infos:
            item = ItjuziItem()
            item["invse_des"] = i["invse_des"]
            item["com_des"] = i["com_des"]
            item["invse_title"] = i["invse_title"]
            item["money"] = i["money"]
            item["com_name"] = i["name"]
            item["prov"] = i["prov"]
            item["round"] = i["round"]
            item["invse_time"] = str(i["year"])+"-"+str(i["year"])+"-"+str(i["day"])
            item["city"] = i["city"]
            item["com_registered_name"] = i["com_registered_name"]
            item["com_scope"] = i["com_scope"]
            invse_company = []
            for j in i["investor"]:
                invse_company.append(j["name"])
            item["invse_company"] = ",".join(invse_company)
            yield item

4.编写PIPELINE:

from itjuzi.settings import DATABASE_DB, DATABASE_HOST, DATABASE_PORT, DATABASE_PWD, DATABASE_USER
import pymysql

class ItjuziPipeline(object):
    def __init__(self):
        host = DATABASE_HOST
        port = DATABASE_PORT
        user = DATABASE_USER
        passwd = DATABASE_PWD
        db = DATABASE_DB
        try:
            self.conn = pymysql.Connect(host=host, port=port, user=user, passwd=passwd, db=db, charset='utf8')
        except Exception as e:
            print("连接数据库出错,错误原因%s"%e)
        self.cur = self.conn.cursor()

    def process_item(self, item, spider):
        params = [item['com_name'], item['com_registered_name'], item['com_des'], item['com_scope'],
                  item['prov'], item['city'], item['round'], item['money'], item['invse_company'],item['invse_des'],item['invse_time'],item['invse_title']]
        try:
            com = self.cur.execute(
                'insert into juzi(com_name, com_registered_name, com_des, com_scope, prov, city, round, money, invse_company, invse_des, invse_time, invse_title)values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',params)
            self.conn.commit()
        except Exception as e:
            print("插入数据出错,错误原因%s" % e)
        return item

    def close_spider(self, spider):
        self.cur.close()
        self.conn.close()

5.编写settings.py

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

# Scrapy settings for itjuzi 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 = 'itjuzi'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'itjuzi (+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 = 0.25
# 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 = {
#    'itjuzi.middlewares.ItjuziSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   # 'itjuzi.middlewares.ItjuziDownloaderMiddleware': 543,
   'itjuzi.middlewares.RandomUserAgent': 102,
   'itjuzi.middlewares.RandomProxy': 103,
}

# 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 = {
    'itjuzi.pipelines.ItjuziPipeline': 100,
}

# 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'
JUZI_USER = "1871111111111"
JUZI_PWD = "123456789"

DATABASE_HOST = '数据库ip'
DATABASE_PORT = 3306
DATABASE_USER = '数据库用户名'
DATABASE_PWD = '数据库密码'
DATABASE_DB = '数据表'

USER_AGENTS = [
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
    "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
    "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
    "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.29 Safari/537.36"
    ]

PROXIES = [
    {'ip_port': '代理ip:代理IP端口', 'user_passwd': '代理ip用户名:代理ip密码'},
    {'ip_port': '代理ip:代理IP端口', 'user_passwd': '代理ip用户名:代理ip密码'},
    {'ip_port': '代理ip:代理IP端口', 'user_passwd': '代理ip用户名:代理ip密码'},
]

6.让项目跑起来:

E:\>scrapy crawl juzi

7.结果展示:


PS:详情信息这里没有爬取,详情信息主要是根据上面列表页返回的json数据中每个公司的id来爬取,详情页的数据可以不用登录就能拿到如:https://www.itjuzi.com/api/investevents/10262327https://www.itjuzi.com/api/get_investevent_down/10262327,还有最重要的一点是如果你的账号不是vip会员的话只能爬取前3页数据这个有点坑,其他的信息模块也是一样的分析方法,需要的可以自己去分析爬取。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,240评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,328评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,182评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,121评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,135评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,093评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,013评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,854评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,295评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,513评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,678评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,398评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,989评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,636评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,801评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,657评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,558评论 2 352