(實戰(zhàn)項目三)新浪網(wǎng)分類資訊爬蟲
爬取新浪網(wǎng)導航頁所有下所有大類、小類侦锯、小類里的子鏈接驼鞭,以及子鏈接頁面的新聞內(nèi)容。
效果演示圖:
items.py
import scrapy
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class SinaItem(scrapy.Item):
# 大類的標題 和 url
parentTitle = scrapy.Field()
parentUrls = scrapy.Field()
# 小類的標題 和 子url
subTitle = scrapy.Field()
subUrls = scrapy.Field()
# 小類目錄存儲路徑
subFilename = scrapy.Field()
# 小類下的子鏈接
sonUrls = scrapy.Field()
# 文章標題和內(nèi)容
head = scrapy.Field()
content = scrapy.Field()
spiders/sina.py
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from Sina.items import SinaItem
import scrapy
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class SinaSpider(scrapy.Spider):
name= "sina"
allowed_domains= ["sina.com.cn"]
start_urls= [
"http://news.sina.com.cn/guide/"
]
def parse(self, response):
items= []
# 所有大類的url 和 標題
parentUrls = response.xpath('//div[@id=\"tab01\"]/div/h3/a/@href').extract()
parentTitle = response.xpath("http://div[@id=\"tab01\"]/div/h3/a/text()").extract()
# 所有小類的ur 和 標題
subUrls = response.xpath('//div[@id=\"tab01\"]/div/ul/li/a/@href').extract()
subTitle = response.xpath('//div[@id=\"tab01\"]/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(subUrls)):
item = SinaItem()
# 保存大類的title和urls
item['parentTitle'] = parentTitle[i]
item['parentUrls'] = parentUrls[i]
# 檢查小類的url是否以同類別大類url開頭终议,如果是返回True (sports.sina.com.cn 和 sports.sina.com.cn/nba)
if_belong = subUrls[j].startswith(item['parentUrls'])
# 如果屬于本大類,將存儲目錄放在本大類目錄下
if(if_belong):
subFilename =parentFilename + '/'+ subTitle[j]
# 如果目錄不存在葱蝗,則創(chuàng)建目錄
if(not os.path.exists(subFilename)):
os.makedirs(subFilename)
# 存儲 小類url穴张、title和filename字段數(shù)據(jù)
item['subUrls'] = subUrls[j]
item['subTitle'] =subTitle[j]
item['subFilename'] = subFilename
items.append(item)
#發(fā)送每個小類url的Request請求,得到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)
#對于返回的小類的url两曼,再進行遞歸請求
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)):
# 檢查每個鏈接是否以大類url開頭皂甘、以.shtml結(jié)尾,如果是返回True
if_belong = sonUrls[i].endswith('.shtml') and sonUrls[i].startswith(meta_1['parentUrls'])
# 如果屬于本大類悼凑,獲取字段值放在同一個item下便于傳輸
if(if_belong):
item = SinaItem()
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ā)送每個小類下子鏈接url的Request請求偿枕,得到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ù)解析方法璧瞬,獲取文章標題和內(nèi)容
def detail_parse(self, response):
item = response.meta['meta_2']
content = ""
head = response.xpath('//h1[@id=\"main_title\"]/text()')
content_list = response.xpath('//div[@id=\"artibody\"]/p/text()').extract()
# 將p標簽里的文本內(nèi)容合并到一起
for content_one in content_list:
content += content_one
item['head']= head
item['content']= content
yield item
pipelines.py
from scrapy import signals
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class SinaPipeline(object):
def process_item(self, item, spider):
sonUrls = item['sonUrls']
# 文件名為子鏈接url中間部分,并將 / 替換為 _渐夸,保存為 .txt格式
filename = sonUrls[7:-6].replace('/','_')
filename += ".txt"
fp = open(item['subFilename']+'/'+filename, 'w')
fp.write(item['content'])
fp.close()
return item
settings.py
BOT_NAME = 'Sina'
SPIDER_MODULES = ['Sina.spiders']
NEWSPIDER_MODULE = 'Sina.spiders'
ITEM_PIPELINES = {
'Sina.pipelines.SinaPipeline': 300,
}
LOG_LEVEL = 'DEBUG'
在項目根目錄下新建main.py文件,用于調(diào)試
from scrapy import cmdline
cmdline.execute('scrapy crawl sina'.split())
執(zhí)行程序
py2 main.py