主要爬取了編程欄目裏的其他編程裏的36638條數據
過程是自己一步一步的往下寫的,有不懂的也是一邊找筆記,一邊百度,一邊調試。
遺憾:沒有進行多欄目數據的爬取,只爬了一個欄目的數據,希望有想法的有鑽研精神的可以自己去嘗試爬取一下,難度應該不會很大。
給一張效果圖:
爬取字段:標題,標題鏈接,標題描述,發佈時間,發佈類型,發佈tag
爬取方式:主要是獲取div【pull-left ltxt w658】下的內容,這個div還是有點複雜的?對於我而言吧。調試了多次,
需要爬取的內容都在上面圖片標記着了,
先上items裏面的代碼:
# -*- 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 MakedreamItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 文章標題
articleTitle = scrapy.Field()
# 文章標題url
articleUrl = scrapy.Field()
# 文章描述
articleDesc = scrapy.Field()
# 文章發佈時間
articlePublic = scrapy.Field()
# 文章類型
articleType = scrapy.Field()
# 文章標籤
articleTag = scrapy.Field()
# pass
沒毛病,我們繼續接着上spider裏面的代碼,瞧仔細了。
# encoding=utf8
import scrapy
from makedream.items import MakedreamItem
class DramingNet(scrapy.Spider):
# 啓動爬蟲的名稱
name = 'draming'
# 爬蟲的域範圍
allowed_domains = ['zhimengzhe.com']
# 爬蟲的第一個url
start_urls = ['http://www.zhimengzhe.com/bianchengjiaocheng/qitabiancheng/index_{}.html'.format(n) for n in
range(0, 1466)]
# 爬取結果解析
def parse(self, response):
base_url = 'http://www.zhimengzhe.com'
# print(response.body)
node_list = response.xpath("//ul[@class='list-unstyled list-article']/li")
for node in node_list:
item = MakedreamItem()
nextNode = node.xpath("./div[@class='pull-left ltxt w658']")
print('*' * 30)
title = nextNode.xpath('./h3/a/text()').extract()
link = nextNode.xpath('./h3/a/@href').extract()
desc = nextNode.xpath('./p/text()').extract()
# 創建時間,類型,標籤
publicTime = nextNode.xpath("./div[@class='tagtime']/span[1]/text()").extract()
publicType = nextNode.xpath("./div[@class='tagtime']/span[2]/a/text()").extract()
publicTag = nextNode.xpath("./div[@class='tagtime']/span[3]/a/text()").extract()
# node
titleLink = base_url + ''.join(link)
item['articleTitle'] = title
# 文章標題url
item['articleUrl'] = titleLink
# 文章描述
item['articleDesc'] = desc
# 文章發佈時間
item['articlePublic'] = publicTime
# 文章類型
item['articleType'] = publicType
# 文章標籤
item['articleTag'] = publicTag
yield item
雖然我這次能成功爬取出來字段,不代表以後也一直可以通用,大家要學會靈活一下, 難道不是嘛。/kb
下載文件裏面的我分別寫了份存入mongodb 和 存入json文件裏面的, mongodb的配置不是很難哦。
# -*- 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 json
import pymongo
from scrapy.conf import settings
class MakedreamPipeline(object):
def process_item(self, item, spider):
return item
class DreamMongo(object):
def __init__(self):
self.client = pymongo.MongoClient(host=settings['MONGO_HOST'], port=settings['MONGO_PORT'])
self.db = self.client[settings['MONGO_DB']]
self.post = self.db[settings['MONGO_COLL']]
def process_item(self, item, spider):
postItem = dict(item)
self.post.insert(postItem)
return item
# 寫入json文件類
class JsonWritePipeline(object):
def __init__(self):
self.file = open('織夢網其他編程.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item
def spider_closed(self, spider):
self.file.close()
注意這裏的settings的導入。
接下來我們看看settings裏面的東西:
主要是mongodb的東東吧,
# -*- coding: utf-8 -*-
# Scrapy settings for makedream 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 = 'makedream'
SPIDER_MODULES = ['makedream.spiders']
NEWSPIDER_MODULE = 'makedream.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'makedream (+http://www.yourdomain.com)'
# 配置mongoDB
MONGO_HOST = "127.0.0.1" # 主機IP
MONGO_PORT = 27017 # 端口號
MONGO_DB = "DreamDB" # 庫名
MONGO_COLL = "Dream_info" # collection
# 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',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'makedream.middlewares.MakedreamSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'makedream.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 = {
# 'makedream.pipelines.MakedreamPipeline': 300,
'makedream.pipelines.JsonWritePipeline':300,
'makedream.pipelines.DreamMongo':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'
接下來就是快到大結局了:
在當前項目下輸入:scrapy crawl draming(爬蟲名稱) 就可以了。然後你就可以去看數據庫,或者看到一個json文件的生成了。
給大夥瞧一下數據庫。
接下來是:根據別人的教程深入學習一下scrap進行全站的抓取吧,感覺這個難度還是要有的,(包括一些cookie,代理ip,user-agent的學習)