鳳凰網(wǎng)分類爬蟲

1. pycharm開發(fā)工具+python2.7+scrapy框架

2.項(xiàng)目開發(fā)

2.1 創(chuàng)建項(xiàng)目

scrapy startproject Ifeng

image.png

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)留言

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市福也,隨后出現(xiàn)的幾起案子局骤,更是在濱河造成了極大的恐慌,老刑警劉巖暴凑,帶你破解...
    沈念sama閱讀 206,482評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件峦甩,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡现喳,警方通過查閱死者的電腦和手機(jī)凯傲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來嗦篱,“玉大人冰单,你說我怎么就攤上這事【拇伲” “怎么了诫欠?”我有些...
    開封第一講書人閱讀 152,762評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)腿宰。 經(jīng)常有香客問我呕诉,道長(zhǎng)缘厢,這世上最難降的妖魔是什么吃度? 我笑而不...
    開封第一講書人閱讀 55,273評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮贴硫,結(jié)果婚禮上椿每,老公的妹妹穿的比我還像新娘剑刑。我一直安慰自己炼绘,他們只是感情好蕉世,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,289評(píng)論 5 373
  • 文/花漫 我一把揭開白布凌净。 她就那樣靜靜地躺著芒澜,像睡著了一般巴粪。 火紅的嫁衣襯著肌膚如雪卒废。 梳的紋絲不亂的頭發(fā)上徒河,一...
    開封第一講書人閱讀 49,046評(píng)論 1 285
  • 那天多律,我揣著相機(jī)與錄音痴突,去河邊找鬼。 笑死狼荞,一個(gè)胖子當(dāng)著我的面吹牛辽装,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播相味,決...
    沈念sama閱讀 38,351評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼拾积,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起拓巧,我...
    開封第一講書人閱讀 36,988評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤斯碌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后肛度,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體输拇,經(jīng)...
    沈念sama閱讀 43,476評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,948評(píng)論 2 324
  • 正文 我和宋清朗相戀三年贤斜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了策吠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,064評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡瘩绒,死狀恐怖猴抹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情锁荔,我是刑警寧澤蟀给,帶...
    沈念sama閱讀 33,712評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站阳堕,受9級(jí)特大地震影響跋理,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜恬总,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,261評(píng)論 3 307
  • 文/蒙蒙 一前普、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧壹堰,春花似錦拭卿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,264評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谆焊,卻和暖如春惠桃,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背辖试。 一陣腳步聲響...
    開封第一講書人閱讀 31,486評(píng)論 1 262
  • 我被黑心中介騙來泰國(guó)打工辜王, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人剃执。 一個(gè)月前我還...
    沈念sama閱讀 45,511評(píng)論 2 354
  • 正文 我出身青樓誓禁,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親肾档。 傳聞我的和親對(duì)象是個(gè)殘疾皇子摹恰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,802評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容