Scrapy网络爬虫框架实战[以腾讯新闻网为例]

超、凢脫俗 2022-07-16 01:22 497阅读 0赞

本博客为原创博客,仅供技术学习使用。不经允许禁止复制下来,传到百度文库等平台。

目录

  • 引言
  • 待爬的url
  • 框架架构
  • items的编写
  • Spider的编写
  • 存储pipelines的编写
  • 相关配置settings的编写
  • main方法的编写
  • 运行结果展示

引言

关于Scrapy的相关介绍及豆瓣案例请看我写的另外两篇博客。
http://blog.csdn.net/qy20115549/article/details/52528896
http://blog.csdn.net/qy20115549/article/details/52575291

待爬的url

如下图所示,所需要爬去的url地址,有很多,存储在txt文本文件中,如其中的一个链接为:http://stock.qq.com/a/20160919/007925.htm。

这里写图片描述

框架架构

这里写图片描述

items的编写

为了简单起见,我只爬了新闻的标题及正文。如下图所示:

这里写图片描述

  1. __author__ = ' HeFei University of Technology Qian Yang email:1563178220@qq.com'
  2. # -*- coding: utf-8 -*-
  3. import scrapy
  4. class News(scrapy.Item):
  5. content = scrapy.Field()
  6. title = scrapy.Field()

Spider的编写

  1. __author__ = ' HeFei University of Technology Qian Yang email:1563178220@qq.com'
  2. # -*- coding:utf-8 -*-
  3. import scrapy
  4. from tengxunnews.items import News
  5. class Teng(scrapy.Spider):
  6. name = 'tengxunnews'
  7. allowed_domains = ["qq.com"]
  8. #read url from file
  9. f = open("E:\\a.txt", "r")
  10. start_urls = []
  11. while True:
  12. line = f.readline()
  13. if line:
  14. pass # do something here
  15. line=line.strip().replace("['","").replace("']","")
  16. p=line.rfind('.')
  17. filename=line[0:p]
  18. print "the url is %s"%line
  19. start_urls.append(line)
  20. else:
  21. break
  22. f.close()
  23. def parse(self, response):
  24. item = News()
  25. item['content'] = response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p/text()').extract()
  26. item['title'] = response.xpath('//div[@class="hd"]/h1/text()').extract()
  27. yield item

存储pipelines的编写

  1. __author__ = ' HeFei University of Technology Qian Yang email:1563178220@qq.com'
  2. # -*- coding: utf-8 -*-
  3. import json
  4. import codecs
  5. #以Json的形式存储
  6. class JsonWithEncodingCnblogsPipeline(object):
  7. def __init__(self):
  8. self.file = codecs.open('tengxunnews.json', 'w', encoding='gbk')
  9. def process_item(self, item, spider):
  10. line = json.dumps(dict(item), ensure_ascii=False) + "\n"
  11. self.file.write(line)
  12. return item
  13. def spider_closed(self, spider):
  14. self.file.close()
  15. #将数据存储到mysql数据库
  16. from twisted.enterprise import adbapi
  17. import MySQLdb
  18. import MySQLdb.cursors
  19. class MySQLStorePipeline(object):
  20. #数据库参数
  21. def __init__(self):
  22. dbargs = dict(
  23. host = '127.0.0.1',
  24. db = 'test',
  25. user = 'root',
  26. passwd = '112233',
  27. cursorclass = MySQLdb.cursors.DictCursor,
  28. charset = 'utf8',
  29. use_unicode = True
  30. )
  31. self.dbpool = adbapi.ConnectionPool('MySQLdb',**dbargs)
  32. ''' The default pipeline invoke function '''
  33. def process_item(self, item,spider):
  34. res = self.dbpool.runInteraction(self.insert_into_table,item)
  35. return item
  36. #插入的表,此表需要事先建好
  37. def insert_into_table(self,conn,item):
  38. conn.execute('insert into tengxunnews(content, title) values(%s,%s)', (
  39. item['content'][0],
  40. item['title'][0])
  41. )

相关配置settings的编写

settings主要放配置方面的文件,如下为我在setting末尾添加的配置代码。

  1. #USER_AGENT
  2. USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
  3. # start MySQL database configure setting
  4. MYSQL_HOST = 'localhost'
  5. MYSQL_DBNAME = 'test'
  6. MYSQL_USER = 'root'
  7. MYSQL_PASSWD = '11223'
  8. # end of MySQL database configure setting
  9. ITEM_PIPELINES = {
  10. 'tengxunnews.pipelines.JsonWithEncodingCnblogsPipeline': 300,
  11. 'tengxunnews.pipelines.MySQLStorePipeline': 300,
  12. }

main方法的编写

  1. __author__ = ' HeFei University of Technology Qian Yang email:1563178220@qq.com'
  2. from scrapy import cmdline
  3. cmdline.execute("scrapy crawl tengxunnews".split())

运行结果展示

这里写图片描述

有问题请联系:合肥工业大学 管理学院 钱洋 1563178220@qq.com

发表评论

表情:
评论列表 (有 0 条评论,497人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Scrapy - 爬虫框架

    Scrapy,Python开发的一个快速,高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可以用于数据挖掘、监测和 [自