首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

python爬虫实例——用scarpy框架爬取全部新浪新闻

使用scrapy框架爬取新浪网导航页所有的大类,小类的子链接,取出链接页面新闻内容。

python版本3.5

回头细查,在爬虫.py里面,明显将搜狗的域名写错,写成了“sougou.com”,而后面要爬取的url是“sogou.com/xxxxxx”,所以报错。

首先终端中运行 scrapy startproject sinanews (项目名)

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和标题名称(创建文件夹用) 以及文章内容和标题

importscrapyclassSinanewsItem(scrapy.Item):# 大类的标题 和 urlparentTitle = scrapy.Field() parentUrls = scrapy.Field()# 小类的标题 和 urlsubTitle= scrapy.Field() subUrls = scrapy.Field()# 小类目录存储路径subFilename = scrapy.Field()# 小类下的子链接sonUrls = scrapy.Field()# 文章标题和内容head = scrapy.Field() content = scrapy.Field()

spider.py文件中全部代码

# -*- coding: utf-8 -*-importscrapyfrom..itemsimportSinanewsItemimportosclassSinaSpider(scrapy.Spider): name ='sina'# allowed_domains = ['news.sina.com']start_urls = ['http://news.sina.com.cn/guide']defparse(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()# 爬取所有大类foriinrange(,len(parentTitle)):# 指定大类目录的路径和目录名parentFilename ="/Users/apple/Desktop/sina/"+ parentTitle[i]# 如果目录不存在,则创建目录if(notos.path.exists(parentFilename)): os.makedirs(parentFilename)# 爬取所有小类forjinrange(,len(subUrls)): item = SinanewsItem()# 保存大类的title和urlsitem['parentTitle'] = parentTitle[i] item['parentUrls'] = parentUrls[i]# 检查小类的url是否 以同类别大类url开头,如果是返回Trueif_belong = subUrls[j].startswith(item['parentUrls'])# 如果属于本大类,将存储目录放在本大类目录下if(if_belong): subFilename = parentFilename +'/'+ subTitle[j]# 如果目录不存在,则创建目录if(notos.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方法处理foriteminitems:yieldscrapy.Request(url= item['subUrls'],meta={'meta_1':item},callback=self.second_parse)defsecond_parse(self,response):# 提取每次Response的meta数据meta_1 = response.meta['meta_1']# 取出小类里面的所有子链接sonUrls = response.xpath('//a/@href').extract() items = []foriinrange(,len(sonUrls)):# 检查每个链接是否以大类url开头、以shtml结尾,如果是返回Trueif_belong = sonUrls[i].endswith('.shtml')andsonUrls[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_parseforiteminitems:yieldscrapy.Request(url=item['sonUrls'],meta={'meta_2':item},callback=self.detail_parse)# 数据解析方法,获取文章标题和内容defdetail_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标签里的文本内容合并到一起forcontent_oneincontent_list: content += content_one item['head'] = head item['content'] = contentyielditem

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.htmlfromscrapyimportsignalsclassSinanewsSpiderMiddleware(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.@classmethoddeffrom_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)returnsdefprocess_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 Nonedefprocess_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.foriinresult:yieldidefprocess_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.passdefprocess_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).forrinstart_requests:yieldrdefspider_opened(self,spider): spider.logger.info('Spider opened: %s'% spider.name)classSinanewsDownloaderMiddleware(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.@classmethoddeffrom_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)returnsdefprocess_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 calledreturn Nonedefprocess_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 IgnoreRequestreturnresponsedefprocess_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() chainpassdefspider_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

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180324G0ZWRS00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券