用scrapy和requests分别爬取内涵社区

最近分别使用了scrapy和requests对内涵社区的爬取,这个网站比较简单,并斌那个没有什反爬策略,简单的思路就是获取数据的网页远吗对其中的json数据解析,然后存储数据。
这里写图片描述
这里写图片描述

下面是scrapy的源码

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

import scrapy

from neihan.items import NeihanItem


class XmSpiderSpider(scrapy.Spider):
    name = "xm_spider"
    allowed_domains = ["neihanshequ.com/"]
    start_urls = ['http://neihanshequ.com/joke/?is_json=1&app_name=neihanshequ_web&max_time=1507809901.0']

    def parse(self, response):
        sites = json.loads(response.body_as_unicode())
        max_num = sites['data']['max_time']
        for group in sites ['data']['data']:
            item = NeihanItem()
            item['data'] = group['group']['text']
            item['title'] = group['group']['user']['name']
            yield item
            # print(title ,data)
        max_url = 'http://neihanshequ.com/joke/?is_json=1&app_name=neihanshequ_web&' + str(max_num)
        yield  scrapy.Request(url= max_url ,callback=self.parse,dont_filter= True  )

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

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

import scrapy


class NeihanItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    data = scrapy.Field()
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.conf import settings


class NeihanPipeline(object):
    def __init__(self):
        host = settings['MONGODB_HOST']
        port = settings['MONGODB_PORT']
        dbName = settings['MONGODB_DBNAME']
        client = pymongo.MongoClient(host=host, port=port)
        tdb = client[dbName]
        self.post = tdb[settings['MONGODB_DOCNAME']]

    def process_item(self, item, spider):
        neihan = dict(item)
        self.post.insert(neihan)
        return item
# -*- coding: utf-8 -*-

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

BOT_NAME = 'neihan'

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

MONGODB_HOST = '127.0.0.1'
MONGODB_PORT = 27017
MONGODB_DBNAME = 'neihan'
MONGODB_DOCNAME = 'duanzi'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'neihan (+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 http://scrapy.readthedocs.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',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'neihan.middlewares.NeihanSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'neihan.middlewares.MyCustomDownloaderMiddleware': 543,
#}

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

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'neihan.pipelines.NeihanPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://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 http://scrapy.readthedocs.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'

下面的是requests的方法

# coding:utf-8
import json

import requests
from bs4 import BeautifulSoup
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36"
                  " (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
}

url = 'http://neihanshequ.com/joke/?is_json=1&app_name=neihanshequ_web&max_time=1507794658.0'
def parse_url(url):
    response = requests.get(url, headers=headers).json()
    # soup = BeautifulSoup(response.text,'lxml')
    # html = json.loads(str(response) )
    for group in response['data']['data']:
        data = group['group']['text']
        print(data)

        save_data(data)

    max_num = str(response['data']['max_time'])
    max_url = 'http://neihanshequ.com/joke/?is_json=1&app_name=neihanshequ_web&'+max_num
    # print(max_url )
    parse_url(max_url )

def get_page(url):
    try:
        str_data = parse_url(url)
    except Exception as e:
        print(e)
        str_data = None
    return str_data
def save_data(data_list):
    with open('neihan.txt', 'a',encoding= "utf-8")as f:
        f.write(data_list  + '\n')
        # f.closed()

if __name__ =="__main__":
    data = get_page(url)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值