zoukankan      html  css  js  c++  java
  • 【转载】Scrapy安装及demo测试笔记

    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:WindowsSystem32目录下


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

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


    2.设置items

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

    3.编写 spider

    [python] view plain copy
    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.       
    12.     def parse(self, response):  
    13.         news_page_num = 14  
    14.         page_num = 386  
    15.         if response.status == 200:  
    16.             for i in range(2,page_num+1):  
    17.                 for j in range(1,news_page_num+1):  
    18.                     item = MyscrapyItem()   
    19.                     item['news_url'],item['news_title'],item['news_date'] = response.xpath(  
    20.                     "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"  
    21.                     "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"  
    22.                     "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()  
    23.                     
    24.                     yield item  
    25.                       
    26.                 next_page_url = "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/"+str(i)+"/list.htm"  
    27.                 yield scrapy.Request(next_page_url,callback=self.parse_news)  
    28.           
    29.     def parse_news(self, response):  
    30.         news_page_num = 14  
    31.         if response.status == 200:  
    32.             for j in range(1,news_page_num+1):  
    33.                 item = MyscrapyItem()  
    34.                 item['news_url'],item['news_title'],item['news_date'] = response.xpath(  
    35.                 "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"  
    36.                 "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"  
    37.                 "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()  
    38.                 yield item  

    4.编写pipelines

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

    5.编写settings.py

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

    6.进到D: mpmyscrapymyscrapyspiders启动爬虫并查看结果: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:WindowsSystem32目录下


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

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


    2.设置items

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

    3.编写 spider

    [python] view plain copy
    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.       
    12.     def parse(self, response):  
    13.         news_page_num = 14  
    14.         page_num = 386  
    15.         if response.status == 200:  
    16.             for i in range(2,page_num+1):  
    17.                 for j in range(1,news_page_num+1):  
    18.                     item = MyscrapyItem()   
    19.                     item['news_url'],item['news_title'],item['news_date'] = response.xpath(  
    20.                     "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"  
    21.                     "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"  
    22.                     "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()  
    23.                     
    24.                     yield item  
    25.                       
    26.                 next_page_url = "http://news.njupt.edu.cn/s/222/t/1100/p/1/c/6866/i/"+str(i)+"/list.htm"  
    27.                 yield scrapy.Request(next_page_url,callback=self.parse_news)  
    28.           
    29.     def parse_news(self, response):  
    30.         news_page_num = 14  
    31.         if response.status == 200:  
    32.             for j in range(1,news_page_num+1):  
    33.                 item = MyscrapyItem()  
    34.                 item['news_url'],item['news_title'],item['news_date'] = response.xpath(  
    35.                 "//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/font/text()"  
    36.                 "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//td[@class='postTime']/text()"  
    37.                 "|//div[@id='newslist']/table[1]/tr["+str(j)+"]//a/@href").extract()  
    38.                 yield item  

    4.编写pipelines

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

    5.编写settings.py

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

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

  • 相关阅读:
    Android自定义之仿360Root大师水纹效果
    Android之TextView的Span样式源码剖析
    Android之TextView的样式类Span的使用详解
    随着ScrollView的滑动,渐渐的执行动画View
    仿微信主界面导航栏图标字体颜色的变化
    android自定义之 5.0 风格progressBar
    Android性能优化之内存篇
    Android性能优化之运算篇
    How to install Zabbix5.0 LTS version with Yum on the CentOS 7.8 system?
    How to install Zabbix4.0 LTS version with Yum on the Oracle Linux 7.3 system?
  • 原文地址:https://www.cnblogs.com/vectors07/p/7979267.html
Copyright © 2011-2022 走看看