1. pycharm開發(fā)工具+python2.7+scrapy框架
2.項(xiàng)目開發(fā)
2.1 創(chuàng)建項(xiàng)目
scrapy startproject Ifeng
2.2 寫自己需要的參數(shù),在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 IfengdataItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 大類的標(biāo)題 和 url
parentTitle = scrapy.Field()
parentUrls = scrapy.Field()
# 小類的標(biāo)題 和 子url
subTitle = scrapy.Field()
subUrls = scrapy.Field()
# 小類目錄存儲(chǔ)路徑
subFilename = scrapy.Field()
# 小類下的子鏈接
sonUrls = scrapy.Field()
# 文章標(biāo)題和內(nèi)容
head = scrapy.Field()
content = scrapy.Field()
pass
2.2 在spider子目錄下新建爬蟲開始文件,我這里命名為ifeng.py
#coding=utf-8
import scrapy
from ifengdata.items import IfengdataItem
import os
class ifengdata(scrapy.Spider):
name='ifeng'
allowed_domains = ["ifeng.com"]
start_urls = [
"http://www.ifeng.com/daohang/"
]
def parse(self, response):
items=[]
#所有的大標(biāo)題和url
parentUrls = response.xpath('//div[@class="col3"]/h2/a/@href').extract()
parentTitle = response.xpath('//div[@class="col3"]/h2/a/text()').extract()
# 所有小類的ur 和 標(biāo)題
subUrls = response.xpath('//div[@class="col3"]/div/div/div/div/ul/li/a/@href').extract()
subTitle= response.xpath('//div[@class="col3"]/div/div/div/div/ul/li/a/text()').extract()
for i in range(0,len(parentTitle)):
# 指定大類目錄的路徑和目錄名
parentFilename = "./Data/" + parentTitle[i]
# 如果目錄不存在呼巷,則創(chuàng)建目錄
if (not os.path.exists(parentFilename)):
os.makedirs(parentFilename)
for j in range(0,len(subTitle)):
item = IfengdataItem()
item['parentUrls']=parentUrls[i]
item['parentTitle']=parentTitle[i]
# yield item
# 檢查小類的url是否以同類別大類url開頭瘪匿,如果是返回True (sports.sina.com.cn 和 sports.sina.com.cn/nba)
if_belong = subUrls[j].startswith(item['parentUrls'])
# 如果屬于本大類仔戈,將存儲(chǔ)目錄放在本大類目錄下
if (if_belong):
subFilename = parentFilename + '/' + subTitle[j]
# 如果目錄不存在边器,則創(chuàng)建目錄
if (not os.path.exists(subFilename)):
os.makedirs(subFilename)
# 存儲(chǔ) 小類url撼短、title和filename字段數(shù)據(jù)
item['subUrls'] = subUrls[j]
item['subTitle'] = subTitle[j]
item['subFilename'] = subFilename
items.append(item)
# 發(fā)送每個(gè)小類url的Request請(qǐng)求靶擦,得到Response連同包含meta數(shù)據(jù) 一同交給回調(diào)函數(shù) second_parse 方法處理
for item in items:
yield scrapy.Request(url=item['subUrls'], meta={'meta_1': item}, callback=self.second_parse)
def second_parse(self,response):
# 提取每次Response的meta數(shù)據(jù)
meta_1 = response.meta['meta_1']
# 取出小類里所有子鏈接
# 取出小類里所有子鏈接
sonUrls = response.xpath('//a/@href').extract()
items = []
for i in range(0, len(sonUrls)):
# 檢查每個(gè)鏈接是否以大類url開頭腮考、以.shtml結(jié)尾,如果是返回True
if_belong =sonUrls[i].startswith(meta_1['parentUrls'])
# 如果屬于本大類玄捕,獲取字段值放在同一個(gè)item下便于傳輸
if (if_belong):
item = IfengdataItem()
item['parentTitle'] = meta_1['parentTitle']
item['parentUrls'] = meta_1['parentUrls']
item['subUrls'] = meta_1['subUrls']
item['subTitle'] = meta_1['subTitle']
item['subFilename'] = meta_1['subFilename']
item['sonUrls'] = sonUrls[i]
items.append(item)
# 發(fā)送每個(gè)小類下子鏈接url的Request請(qǐng)求踩蔚,得到Response后連同包含meta數(shù)據(jù) 一同交給回調(diào)函數(shù) detail_parse 方法處理
for item in items:
yield scrapy.Request(url=item['sonUrls'], meta={'meta_2': item}, callback=self.detail_parse)
# 數(shù)據(jù)解析方法,獲取文章標(biāo)題和內(nèi)容
def detail_parse(self, response):
item = response.meta['meta_2']
content = ""
head = response.xpath('//h1[@id=\"artical_topic\"]/text()').extract()
content_list = response.xpath('//div[@id=\"main_content\"]/p/text()').extract()
# 將p標(biāo)簽里的文本內(nèi)容合并到一起
for content_one in content_list:
content += content_one
if head!='':
item['head'] = head[0]
print(item['head'])
else :
item['head']=1
item['content'] = content
yield item
2.3配置管道pipelines.py
# -*- 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
import pymysql
from ifengdata import settings
class IfengdataPipeline(object):
def __init__(self):
# host='127.0.0.1'
# port=27017
# client=pymongo.MongoClient(host=host,port=port)
# dbname = 'ifeng'
#
# # pymongo.MongoClient(host, port) 創(chuàng)建MongoDB鏈接
# # 指向指定的數(shù)據(jù)庫
# mdb = client[dbname]
# # 獲取數(shù)據(jù)庫里存放數(shù)據(jù)的表名
# self.post = mdb['ifengdata1']
# 獲取setting主機(jī)名枚粘、端口號(hào)和數(shù)據(jù)庫名
# host = settings['MONGODB_HOST']
# host='127.0.0.1'
# port = settings['MONGODB_PORT']
# port=27017
# dbname = settings['MONGODB_DBNAME']
# dbname='IFeng'
# pymongo.MongoClient(host, port) 創(chuàng)建MongoDB鏈接
# client = pymongo.MongoClient(host=host, port=port)
# 指向指定的數(shù)據(jù)庫
# mdb = client[dbname]
# 獲取數(shù)據(jù)庫里存放數(shù)據(jù)的表名
# self.post = mdb[settings['MONGODB_DOCNAME']]
# self.post= mdb['IFengData']
self.conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='root',
db='test',
charset='utf8',
)
self.cursor=self.conn.cursor()
def process_item(self, item, spider):
item = dict(item)
sql = 'select * from ifengdata4 WHERE mulu=%s'
par =[item['parentTitle']]
name = self.cursor.execute(sql,par)
self.conn.commit()
if name:
pass
else:
sql1='insert into ifengdata4(id,mulu) VALUES(null,%s)'
params=[item['parentTitle']]
self.cursor.execute(sql1,params)
self.conn.commit()
sql4 = 'select * from ifengdata5 WHERE zimulu=%s'
par4 = [item['subTitle']]
name = self.cursor.execute(sql4, par4)
self.conn.commit()
if name:
pass
else:
sql2 = 'insert into ifengdata5(id,zimulu) VALUES(null,%s)'
params2=[item['subTitle']]
self.cursor.execute(sql2, params2)
self.conn.commit()
sql3 = 'insert into ifengdata6(id,title) VALUES(null,%s)'
params3 = [item['head']]
self.cursor.execute(sql3, params3)
self.conn.commit()
return item
2.4設(shè)置settings.py文件
# -*- coding: utf-8 -*-
# Scrapy settings for ifengdata 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 = 'ifengdata'
SPIDER_MODULES = ['ifengdata.spiders']
NEWSPIDER_MODULE = 'ifengdata.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'ifengdata (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# 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 = {
# 'ifengdata.middlewares.IfengdataSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'ifengdata.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 = {
'ifengdata.pipelines.IfengdataPipeline': 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'
# MONGODB 主機(jī)環(huán)回地址127.0.0.1
# MONGODB_HOST = '127.0.0.1'
# 端口號(hào)馅闽,默認(rèn)是27017
# MONGODB_PORT = 27017
# 設(shè)置數(shù)據(jù)庫名稱
# MONGODB_DBNAME = 'IFeng'
# 存放本次數(shù)據(jù)的表名稱
# MONGODB_DOCNAME = 'IFengData'
DOWNLOAD_DELAY = 1
REDIS_HOST = "192.168.13.23"
REDIS_PORT = 6379
可以試一下哦,有問題請(qǐng)留言