Scrapy安装及demo测试笔记

原创 2016年09月01日 16:34:00
 

Scrapy安装及demo测试笔记

一、环境搭建

1. 安装scrapy:pip install scrapy

2.安装:PyWin32,可以从网上载已编译好的安装包:http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#pywin32

安装完之后会报如下错误

解决办法,把以下两个文件拷贝到C:\Windows\System32目录下

二、创建scrapy工程(在此用网上别人提供的例子)

1.cmd的方式进到某个指定目录(d:/tmp/)下执行:scrapy startproject myscrapy,命令执行完之后,生成的目录结构如下

2.设置items

  1. # -*- coding: utf-8 -*-
  2. # Define here the models for your scraped items
  3. #
  4. # See documentation in:
  5. # http://doc.scrapy.org/en/latest/topics/items.html
  6. import scrapy
  7. class MyscrapyItem(scrapy.Item):
  8. news_title = scrapy.Field() #南邮新闻标题
  9. news_date = scrapy.Field()  #南邮新闻时间
  10. news_url = scrapy.Field()   #南邮新闻的详细链接

3.编写 spider

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from myscrapy.items import MyscrapyItem
  4. import logging
  5. class myscrapySpider(scrapy.Spider):
  6. name = "myscrapy"
  7. allowed_domains = ["njupt.edu.cn"]
  8. start_urls = [
  9. "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/1/list.htm",
  10. ]
  11. def parse(self, response):
  12. news_page_num = 14
  13. page_num = 386
  14. if response.status == 200:
  15. for i in range(2,page_num+1):
  16. for j in range(1,news_page_num+1):
  17. item = MyscrapyItem()
  18. item['news_url'],item['news_title'],item['news_date'] = response.xpath(
  19. "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"
  20. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"
  21. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()
  22. yield item
  23. next_page_url = "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/"+str(i)+"/list.htm"
  24. yield scrapy.Request(next_page_url,callback=self.parse_news)
  25. def parse_news(self, response):
  26. news_page_num = 14
  27. if response.status == 200:
  28. for j in range(1,news_page_num+1):
  29. item = MyscrapyItem()
  30. item['news_url'],item['news_title'],item['news_date'] = response.xpath(
  31. "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"
  32. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"
  33. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()
  34. yield item

4.编写pipelines

  1. # -*- coding: utf-8 -*-
  2. # Define your item pipelines here
  3. #
  4. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  5. # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
  6. import json
  7. class MyscrapyPipeline(object):
  8. def __init__(self):
  9. self.file = open('myscrapy.txt',mode='wb')
  10. def process_item(self, item, spider):
  11. self.file.write(item['news_title'].encode("GBK"))
  12. self.file.write("\n")
  13. self.file.write(item['news_date'].encode("GBK"))
  14. self.file.write("\n")
  15. self.file.write(item['news_url'].encode("GBK"))
  16. self.file.write("\n")
  17. return item

5.编写settings.py

  1. # -*- coding: utf-8 -*-
  2. # Scrapy settings for myscrapy project
  3. #
  4. # For simplicity, this file contains only settings considered important or
  5. # commonly used. You can find more settings consulting the documentation:
  6. #
  7. #     http://doc.scrapy.org/en/latest/topics/settings.html
  8. #     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  9. #     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  10. BOT_NAME = 'myscrapy'
  11. SPIDER_MODULES = ['myscrapy.spiders']
  12. NEWSPIDER_MODULE = 'myscrapy.spiders'
  13. # Crawl responsibly by identifying yourself (and your website) on the user-agent
  14. #USER_AGENT = 'myscrapy (+http://www.yourdomain.com)'
  15. # Obey robots.txt rules
  16. ROBOTSTXT_OBEY = True
  17. # Configure maximum concurrent requests performed by Scrapy (default: 16)
  18. #CONCURRENT_REQUESTS = 32
  19. # Configure a delay for requests for the same website (default: 0)
  20. # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
  21. # See also autothrottle settings and docs
  22. #DOWNLOAD_DELAY = 3
  23. # The download delay setting will honor only one of:
  24. #CONCURRENT_REQUESTS_PER_DOMAIN = 16
  25. #CONCURRENT_REQUESTS_PER_IP = 16
  26. # Disable cookies (enabled by default)
  27. #COOKIES_ENABLED = False
  28. # Disable Telnet Console (enabled by default)
  29. #TELNETCONSOLE_ENABLED = False
  30. # Override the default request headers:
  31. #DEFAULT_REQUEST_HEADERS = {
  32. #   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  33. #   'Accept-Language': 'en',
  34. #}
  35. # Enable or disable spider middlewares
  36. # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  37. #SPIDER_MIDDLEWARES = {
  38. #    'myscrapy.middlewares.MyCustomSpiderMiddleware': 543,
  39. #}
  40. # Enable or disable downloader middlewares
  41. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  42. #DOWNLOADER_MIDDLEWARES = {
  43. #    'myscrapy.middlewares.MyCustomDownloaderMiddleware': 543,
  44. #}
  45. # Enable or disable extensions
  46. # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
  47. #EXTENSIONS = {
  48. #    'scrapy.extensions.telnet.TelnetConsole': None,
  49. #}
  50. # Configure item pipelines
  51. # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
  52. ITEM_PIPELINES = {
  53. 'myscrapy.pipelines.MyscrapyPipeline': 1,
  54. }
  55. # Enable and configure the AutoThrottle extension (disabled by default)
  56. # See http://doc.scrapy.org/en/latest/topics/autothrottle.html
  57. #AUTOTHROTTLE_ENABLED = True
  58. # The initial download delay
  59. #AUTOTHROTTLE_START_DELAY = 5
  60. # The maximum download delay to be set in case of high latencies
  61. #AUTOTHROTTLE_MAX_DELAY = 60
  62. # The average number of requests Scrapy should be sending in parallel to
  63. # each remote server
  64. #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
  65. # Enable showing throttling stats for every response received:
  66. #AUTOTHROTTLE_DEBUG = False
  67. # Enable and configure HTTP caching (disabled by default)
  68. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
  69. #HTTPCACHE_ENABLED = True
  70. #HTTPCACHE_EXPIRATION_SECS = 0
  71. #HTTPCACHE_DIR = 'httpcache'
  72. #HTTPCACHE_IGNORE_HTTP_CODES = []
  73. #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

6.进到D:\tmp\myscrapy\myscrapy\spiders启动爬虫并查看结果:scrapy crawl myscrapy

Scrapy安装及demo测试笔记

原创 2016年09月01日 16:34:00
 

Scrapy安装及demo测试笔记

一、环境搭建

1. 安装scrapy:pip install scrapy

2.安装:PyWin32,可以从网上载已编译好的安装包:http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#pywin32

安装完之后会报如下错误

解决办法,把以下两个文件拷贝到C:\Windows\System32目录下

二、创建scrapy工程(在此用网上别人提供的例子)

1.cmd的方式进到某个指定目录(d:/tmp/)下执行:scrapy startproject myscrapy,命令执行完之后,生成的目录结构如下

2.设置items

  1. # -*- coding: utf-8 -*-
  2. # Define here the models for your scraped items
  3. #
  4. # See documentation in:
  5. # http://doc.scrapy.org/en/latest/topics/items.html
  6. import scrapy
  7. class MyscrapyItem(scrapy.Item):
  8. news_title = scrapy.Field() #南邮新闻标题
  9. news_date = scrapy.Field()  #南邮新闻时间
  10. news_url = scrapy.Field()   #南邮新闻的详细链接

3.编写 spider

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from myscrapy.items import MyscrapyItem
  4. import logging
  5. class myscrapySpider(scrapy.Spider):
  6. name = "myscrapy"
  7. allowed_domains = ["njupt.edu.cn"]
  8. start_urls = [
  9. "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/1/list.htm",
  10. ]
  11. def parse(self, response):
  12. news_page_num = 14
  13. page_num = 386
  14. if response.status == 200:
  15. for i in range(2,page_num+1):
  16. for j in range(1,news_page_num+1):
  17. item = MyscrapyItem()
  18. item['news_url'],item['news_title'],item['news_date'] = response.xpath(
  19. "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"
  20. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"
  21. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()
  22. yield item
  23. next_page_url = "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/"+str(i)+"/list.htm"
  24. yield scrapy.Request(next_page_url,callback=self.parse_news)
  25. def parse_news(self, response):
  26. news_page_num = 14
  27. if response.status == 200:
  28. for j in range(1,news_page_num+1):
  29. item = MyscrapyItem()
  30. item['news_url'],item['news_title'],item['news_date'] = response.xpath(
  31. "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"
  32. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"
  33. "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()
  34. yield item

4.编写pipelines

  1. # -*- coding: utf-8 -*-
  2. # Define your item pipelines here
  3. #
  4. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  5. # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
  6. import json
  7. class MyscrapyPipeline(object):
  8. def __init__(self):
  9. self.file = open('myscrapy.txt',mode='wb')
  10. def process_item(self, item, spider):
  11. self.file.write(item['news_title'].encode("GBK"))
  12. self.file.write("\n")
  13. self.file.write(item['news_date'].encode("GBK"))
  14. self.file.write("\n")
  15. self.file.write(item['news_url'].encode("GBK"))
  16. self.file.write("\n")
  17. return item

5.编写settings.py

  1. # -*- coding: utf-8 -*-
  2. # Scrapy settings for myscrapy project
  3. #
  4. # For simplicity, this file contains only settings considered important or
  5. # commonly used. You can find more settings consulting the documentation:
  6. #
  7. #     http://doc.scrapy.org/en/latest/topics/settings.html
  8. #     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  9. #     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  10. BOT_NAME = 'myscrapy'
  11. SPIDER_MODULES = ['myscrapy.spiders']
  12. NEWSPIDER_MODULE = 'myscrapy.spiders'
  13. # Crawl responsibly by identifying yourself (and your website) on the user-agent
  14. #USER_AGENT = 'myscrapy (+http://www.yourdomain.com)'
  15. # Obey robots.txt rules
  16. ROBOTSTXT_OBEY = True
  17. # Configure maximum concurrent requests performed by Scrapy (default: 16)
  18. #CONCURRENT_REQUESTS = 32
  19. # Configure a delay for requests for the same website (default: 0)
  20. # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
  21. # See also autothrottle settings and docs
  22. #DOWNLOAD_DELAY = 3
  23. # The download delay setting will honor only one of:
  24. #CONCURRENT_REQUESTS_PER_DOMAIN = 16
  25. #CONCURRENT_REQUESTS_PER_IP = 16
  26. # Disable cookies (enabled by default)
  27. #COOKIES_ENABLED = False
  28. # Disable Telnet Console (enabled by default)
  29. #TELNETCONSOLE_ENABLED = False
  30. # Override the default request headers:
  31. #DEFAULT_REQUEST_HEADERS = {
  32. #   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  33. #   'Accept-Language': 'en',
  34. #}
  35. # Enable or disable spider middlewares
  36. # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  37. #SPIDER_MIDDLEWARES = {
  38. #    'myscrapy.middlewares.MyCustomSpiderMiddleware': 543,
  39. #}
  40. # Enable or disable downloader middlewares
  41. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  42. #DOWNLOADER_MIDDLEWARES = {
  43. #    'myscrapy.middlewares.MyCustomDownloaderMiddleware': 543,
  44. #}
  45. # Enable or disable extensions
  46. # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
  47. #EXTENSIONS = {
  48. #    'scrapy.extensions.telnet.TelnetConsole': None,
  49. #}
  50. # Configure item pipelines
  51. # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
  52. ITEM_PIPELINES = {
  53. 'myscrapy.pipelines.MyscrapyPipeline': 1,
  54. }
  55. # Enable and configure the AutoThrottle extension (disabled by default)
  56. # See http://doc.scrapy.org/en/latest/topics/autothrottle.html
  57. #AUTOTHROTTLE_ENABLED = True
  58. # The initial download delay
  59. #AUTOTHROTTLE_START_DELAY = 5
  60. # The maximum download delay to be set in case of high latencies
  61. #AUTOTHROTTLE_MAX_DELAY = 60
  62. # The average number of requests Scrapy should be sending in parallel to
  63. # each remote server
  64. #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
  65. # Enable showing throttling stats for every response received:
  66. #AUTOTHROTTLE_DEBUG = False
  67. # Enable and configure HTTP caching (disabled by default)
  68. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
  69. #HTTPCACHE_ENABLED = True
  70. #HTTPCACHE_EXPIRATION_SECS = 0
  71. #HTTPCACHE_DIR = 'httpcache'
  72. #HTTPCACHE_IGNORE_HTTP_CODES = []
  73. #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

6.进到D:\tmp\myscrapy\myscrapy\spiders启动爬虫并查看结果:scrapy crawl myscrapy

【转载】Scrapy安装及demo测试笔记的更多相关文章

  1. red5研究(一):下载,工程建立、oflaDemo安装、demo测试

    一.red5下载.添加工程到myeclipse 1,从官网上下载red51.01版本(我下载的是red51.0的版本),下载链接http://www.red5.org/downloads/red5/1 ...

  2. hue安装及基本测试-笔记

    #################################################################################################### ...

  3. c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具

    c#实例化继承类,必须对被继承类的程序集做引用   0x00 问题 类型“Model.NewModel”在未被引用的程序集中定义.必须添加对程序集“Model, Version=1.0.0.0, Cu ...

  4. Python、pip和scrapy的安装——Python爬虫学习笔记1

    Python作为爬虫语言非常受欢迎,近期项目需要,很是学习了一番Python,在此记录学习过程:首先因为是初学,而且当时要求很快速的出demo,所以首先想到的是框架,一番查找选用了Python界大名鼎 ...

  5. Python3 Scrapy 安装方法

    Python3 Scrapy 安装方法 (一脸辛酸泪) 写在前面 最近在学习爬虫,在熟悉了Python语言和BeautifulSoup4后打算下个爬虫框架试试. 没想到啊,这坑太深了... 看了看相关 ...

  6. 02 Linux 下安装JDK并测试开发“Hello World!”

    测试环境 主机系统:Win7 64位 虚拟机:VMware® Workstation 11.1.0 虚拟机系统:CentOS 6.5 64位   Kernel 2.6.32-431.e16.x86_6 ...

  7. Python实用工具包Scrapy安装教程

       对于想用每个想用Python开发网络爬虫的开发者来说,Scrapy无疑是一个极好的开源工具.今天安装之后觉得Scrapy的安装确实不易啊.所以在此博文一篇,往后来着少走弯路. 废话不多说了,如果 ...

  8. Chapter 2. OpenSSL的安装和配置学习笔记

    Chapter 2. OpenSSL的安装和配置学习笔记 2.1 在linux上面安装OpenSSL我还是做点No paper事情比较在行,正好和老师的课程接轨一下.以前尝试过在Windows上面安装 ...

  9. 中标麒麟6.0_ICE3.4.2编译+demo测试(CPP)

    (菜鸟版)确保 gcc版本4.4.6(其他版本未测试),4.8不行 一.降级GCC到4.4.6 注意:gcc g++ c++命令都为4.4.6(可用gcc -v; g++ -v; c++ -v 命令查 ...

随机推荐

  1. numpy(一)

    ndarray np的一个核心类,它描述了相同类型的“项目”集合.可以使用例如N个整数来索引项目.每个项目占用相同大小的内存块, 并且所有块都以完全相同的方式解释. 如何解释数组中的每个项目由单独的数 ...

  2. ZJNU 1196 - 三阶魔方【模拟题】——高级

    大模拟,空想很容易把面和面之间的关系搞混 所以这时候需要自己找一个正方体(实在不行长方体代替)跟着图把每个面正方向标出来 然后模拟6种操作分别会对哪些块进行操作 对于储存数据的想法是,对输入输出进行分 ...

  3. 第一个----关于GPIO的总结

    首先,自己本来报的是单片机的  ,但是因为队友的脑残,给我报成了嵌入式,哎,惨啊,就得从头看这个云里雾里的东西,但是没办法,都报名了  不能呢个交白卷,不然自己就是逃兵了,还有20天就比赛了  我得加 ...

  4. mysql统计指定数据库的各表的条数

    mysql统计指定数据库的各表的条数 SELECT table_schema,table_name,table_rows,CREATE_TIME FROM TABLES WHERE TABLE_SCH ...

  5. IIS设置禁止某个IP或IP段访问网站的方法

    网站被刷,对话接不过来 打开IIS,选中禁IP的站点,找到“ip地址和域限制”这个功能,如果没有安装,打开服务器管理器,点击角色,窗口右边找到添加角色服务,找到“IP和域限制”并勾选安装. 打开ip地 ...

  6. Java注解基础

    0.背景 Java注解--Annotation产生于JDK5.作为code的特殊“标记”,注解可以在编译.类加载.运行时被读取,并执行处理. 开发利用注解在源码中嵌入补充信息,工具(代码分析.开发.部 ...

  7. 简单的使用httpclient读取网页html例子

    public void clientPost(String url) {  /* 1 生成 HttpClinet 对象并设置参数*/    HttpClient httpClient=new Http ...

  8. php对比二个不同的二维数组

    $diff_data = array_filter($data1, function($v) use ($data2) { return ! in_array($v, $data2);});

  9. 五、linux-mysql 下mysql的管理(二)

    1.插入语句: create  table test(  id int(4)  not null auto_increment,  name char(20)  not null,  primary ...

  10. fastjon案例

    --json为json串JSONObject obj = JSON.parseObject(json);String x = obj.getString("cropId");JSO ...