1. 程式人生 > >python爬蟲例項——用scarpy框架爬取全部新浪新聞

python爬蟲例項——用scarpy框架爬取全部新浪新聞

使用scrapy框架爬取新浪網導航頁所有的大類,小類的子連結,取出連結頁面新聞內容。

python版本3.5

注意點:spider檔案中不寫allowed domains,因為後面的子連結的url中跟不包含new.sina.com

爬蟲執行報錯:DEBUG: Filtered offsite request to 'weixin.sogou.com'

報錯原因:
官方對這個的解釋,是要request的地址和allow_domain裡面的衝突,從而被過濾掉。

回頭細查,在爬蟲.py裡面,明顯將搜狗的域名寫錯,寫成了“sougou.com”,而後面要爬取的url是“sogou.com/xxxxxx”,所以報錯。


首先終端中執行 scrapy startproject sinanews (專案名)

然後spider資料夾中建立爬蟲  scrapy genspider sina  ‘new.sina.com’

tree 一下(已經寫好的專案)

.
├── main.py
├── scrapy.cfg
└── sinanews
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   ├── items.cpython-36.pyc
    │   ├── pipelines.cpython-36.pyc
    │   └── settings.cpython-36.
pyc ├── items.py ├── middlewares.py ├── pipelines.py ├── settings.py └── spiders ├── __init__.py ├── __pycache__ │   ├── __init__.cpython-36.pyc │   └── sina.cpython-36.pyc └── sina.py

編輯items.py

定義好要爬取的url和標題名稱(建立資料夾用)  以及文章內容和標題

import scrapy


class 
SinanewsItem(scrapy.Item): # 大類的標題 和 url parentTitle = scrapy.Field() parentUrls = scrapy.Field() # 小類的標題 和 url subTitle= scrapy.Field() subUrls = scrapy.Field() # 小類目錄儲存路徑 subFilename = scrapy.Field() # 小類下的子連結 sonUrls = scrapy.Field() # 文章標題和內容 head = scrapy.Field() content = scrapy.Field()

spider.py檔案中全部程式碼

# -*- coding: utf-8 -*-
import scrapy
from ..items import SinanewsItem
import os


class SinaSpider(scrapy.Spider):
    name = 'sina'
# allowed_domains = ['news.sina.com']
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("//div[@id='tab01']/div/h3/a/text()").extract()

        # 所有小類的url 和 標題
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 = "/Users/apple/Desktop/sina/" + parentTitle[i]
            # 如果目錄不存在,則建立目錄
if(not os.path.exists(parentFilename)):
                os.makedirs(parentFilename)

            # 爬取所有小類
for j in range(0,len(subUrls)):
                item = SinanewsItem()
                # 儲存大類的title和urls
item['parentTitle'] = parentTitle[i]
                item['parentUrls'] = parentUrls[i]

                # 檢查小類的url是否 以同類別大類url開頭,如果是返回True
if_belong = subUrls[j].startswith(item['parentUrls'])

                # 如果屬於本大類,將儲存目錄放在本大類目錄下
if(if_belong):
                    subFilename = parentFilename  + '/' + subTitle[j]

                    # 如果目錄不存在,則建立目錄
if(not os.path.exists(subFilename)):
                        os.makedirs(subFilename)

                    # 儲存 小類url、title和filename欄位資料
item['subUrls'] = subUrls[j]
                    item['subTitle'] = subTitle[j]
                    item['subFilename'] = subFilename
                    items.append(item)

            # 傳送每個小類的url的Request請求,得到Response連同包含meta資料 一同交給回撥函式 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資料
meta_1 = response.meta['meta_1']
        # 取出小類裡面的所有子連結
sonUrls = response.xpath('//a/@href').extract()
        items = []
        for i in range(0,len(sonUrls)):
            # 檢查每個連結是否以大類url開頭、以shtml結尾,如果是返回True
if_belong = sonUrls[i].endswith('.shtml') and sonUrls[i].startswith(meta_1['parentUrls'])

            # 如果屬於本大類,獲取欄位值放在同一個item下便於傳輸
if(if_belong):
                item = SinanewsItem()
                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)

        # 傳送每個小類下子連結url的Request請求,得到response後連同包含meta資料  一同交給回撥函式 detail_parse
for item in items:
            yield scrapy.Request(url=item['sonUrls'],meta={'meta_2':item},callback=self.detail_parse)

    # 資料解析方法,獲取文章標題和內容
def detail_parse(self,response):
        item = response.meta['meta_2']
        content = ""
head = response.xpath('//h1[@class="main-title"]/text()').extract()
        content_list = response.xpath("//div[@class='article']//p/text()").extract()
        # 將p標籤裡的文字內容合併到一起
for content_one in content_list:
            content += content_one
        item['head'] = head
        item['content'] = content
        yield item

pipelines.py檔案全部程式碼

# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals


class SinanewsSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.
@classmethod
def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.
        # Should return None or raise an exception.
return None
    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.
        # Must return an iterable of Request, dict or Item objects.
for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.
        # Should return either None or an iterable of Response, dict
        # or Item objects.
pass
    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.
        # Must return only requests (not items).
for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class SinanewsDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
@classmethod
def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.
        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
return None
    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.
        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.
        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
pass
    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

setting.py中開啟

ITEM_PIPELINES = {
   'sinanews.pipelines.SinanewsPipeline': 300,
}

並將遵循robotstxt協議註釋,否則有些網站怕不下來

# ROBOTSTXT_OBEY = True

然後隨機設定幾個user-agent