python爬虫实例——用scarpy框架爬取全部新浪新闻
2018-03-24 16:56
281 查看
使用scrapy框架爬取新浪网导航页所有的大类,小类的子链接,取出链接页面新闻内容。
python版本3.5
注意点:spider文件中不写allowed domains,因为后面的子链接的url中跟不包含new.sina.com
官方对这个的解释,是要request的地址和allow_domain里面的冲突,从而被过滤掉。回头细查,在爬虫.py里面,明显将搜狗的域名写错,写成了“sougou.com”,而后面要爬取的url是“sogou.com/xxxxxx”,所以报错。
首先终端中运行 scrapy startproject sinanews (项目名)
[b]然后spider文件夹中创建爬虫 scrapy genspider sina ‘new.sina.com’
[/b]
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)
4000
# 存储 小类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
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 (项目名)
[b]然后spider文件夹中创建爬虫 scrapy genspider sina ‘new.sina.com’
[/b]
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)
4000
# 存储 小类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
相关文章推荐
- Python爬虫框架Scrapy实例代码
- python爬虫框架scrapy实例详解
- Python爬虫框架Scrapy实例
- python爬虫框架scrapy实例详解
- Python爬虫框架Scrapy实例
- python爬虫框架scrapy实例详解
- python爬虫框架scrapy实例详解
- python爬虫框架scarpy之AttributeError: module 'scrapy' has no attribute 'spider'
- python爬虫框架scrapy实例详解
- python爬虫实例
- Python爬虫----实例: 抓取百度百科Python词条相关1000个页面数据
- Python爬虫框架Scrapy
- python开源爬虫框架scrapy源码解析(四)
- Python爬虫框架Scrapy实战 - 抓取BOSS直聘招聘信息
- Python爬虫爬取动态页面思路+实例(一)
- [Python]网络爬虫(12):爬虫框架Scrapy的第一个爬虫示例入门教程
- Python实例:网络爬虫抓取豆瓣3万本书(4)
- Python网络爬虫3 ---- ubuntu下安装爬虫框架scrapy
- 深入剖析Python的爬虫框架Scrapy的结构与运作流程
- Python爬虫框架Scrapy实战教程---定向批量获取职位招聘信息