VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • 使用Python爬虫Scrapy框架爬取数据

时隔数月,国庆期间想做个假期旅游的分析展示。

1、通过Python爬取旅游网站上数据,并存储到数据库

2、通过Echart/FineReport/Superset等数据分析工具对数据展示

环境:

Win10

Python:3.7

Scrapy:1.5.1

使用Pycharm开发

Scrapy文档教程中有Scrapy的安装指导,不过在Windows下安装当初确实遇到许多坑

使用方法大致是进入项目的workspace使用命令行创建一个Scrapy项目,这个项目中有Scrapy的配置、模块等

如:


  1.  
    cd E:Pythonworkspace
  2.  
    E:\PythonWorkspace>scrapy startproject project_name

然后会创建project_name的目录


  1.  
    project_name/
  2.  
    scrapy.cfg
  3.  
    project_name/
  4.  
    __init__.py
  5.  
    items.py
  6.  
    pipelines.py
  7.  
    settings.py
  8.  
    spiders/
  9.  
    __init__.py
  10.  
    ...
  11.  
    这些文件分别是:
  12.  
     
  13.  
    scrapy.cfg: 项目的配置文件
  14.  
    project_name/: 该项目的python模块。之后您将在此加入代码。
  15.  
    project_name/items.py: 项目中的item文件.
  16.  
    project_name/pipelines.py: 项目中的pipelines文件.
  17.  
    project_name/settings.py: 项目的设置文件.
  18.  
    project_name/spiders/: 放置spider代码的目录.

拷自文档。。

首先写一个Scrapy项目练手,可按照教程,但URL是被墙了的。

以下代码是获取去哪儿网首页Title

Spider爬虫文件:该爬虫name为test


  1.  
    import scrapy
  2.  
     
  3.  
    class test(scrapy.spiders.Spider):
  4.  
    name = "test"
  5.  
    # allowed_domains = ["qunar"]
  6.  
    start_urls = ["https://www.qunar.com/"]
  7.  
     
  8.  
    def parse(self,response):
  9.  
    title = str(response.xpath('/html/head/title')[0])
  10.  
    print(title)

不出意外的报错。。

坑1:

run该文件无效,什么都没执行。Scrapy项目不执行,但返回值为运行结束

Process finished with exit code 0

Scrapy项目需通过命令行执行,例如在该项目根目录执行 scrapy crawl spider_name

或者在Pycharm中看到init文件,在其中加上


  1.  
    from scrapy import cmdline
  2.  
    cmdline.execute("scrapy crawl spider_name".split());

然后报错:


  1.  
    def write(self, data, async=False):
  2.  
     
  3.  
    ^
  4.  
     
  5.  
    SyntaxError: invalid syntax

按照网上说法,将该文件中所有async改为其他关键词如shark,报错消失,出现


  1.  
    import win32api
  2.  
    ModuleNotFoundError: No module named 'win32api'

Windows系统上安装win32api模块即可,命令行执行,这里通过豆瓣源安装


  1.  
    C:\Users\yinyunqi>pip install -i https://pypi.douban.com/simple pypiwin32
  2.  
    Looking in indexes: https://pypi.douban.com/simple
  3.  
    Collecting pypiwin32
  4.  
    Downloading https://pypi.doubanio.com/packages/d0/1b/2f292bbd742e369a100c91faa0483172cd91a1a422a6692055ac920946c5/pypiwin32-223-py3-none-any.whl
  5.  
    Collecting pywin32>=223 (from pypiwin32)
  6.  
    Downloading https://pypi.doubanio.com/packages/a3/8a/eada1e7990202cd27e58eca2a278c344fef190759bbdc8f8f0eb6abeca9c/pywin32-224-cp37-cp37m-win_amd64.whl (9.0MB)
  7.  
    100% |████████████████████████████████| 9.1MB 260kB/s
  8.  
    Installing collected packages: pywin32, pypiwin32
  9.  
    Successfully installed pypiwin32-223 pywin32-224

重新运行打印如下


  1.  
    E:\Python\Python37\python.exe E:/PythonWorkspace/NationalAna/NationalAna/__init__.py
  2.  
    2018-09-29 14:07:49 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: NationalAna)
  3.  
    2018-09-29 14:07:49 [scrapy.utils.log] INFO: Versions: lxml 4.2.4.0, libxml2 2.9.5, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.7.0, Python 3.7.0b2 (v3.7.0b2:b0ef5c979b, Feb 28 2018, 02:24:20) [MSC v.1912 64 bit (AMD64)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.3, Platform Windows-10-10.0.17134-SP0
  4.  
    2018-09-29 14:07:49 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'NationalAna', 'NEWSPIDER_MODULE': 'NationalAna.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['NationalAna.spiders']}
  5.  
    2018-09-29 14:07:49 [scrapy.middleware] INFO: Enabled extensions:
  6.  
    ['scrapy.extensions.corestats.CoreStats',
  7.  
    'scrapy.extensions.telnet.TelnetConsole',
  8.  
    'scrapy.extensions.logstats.LogStats']
  9.  
    2018-09-29 14:07:50 [scrapy.middleware] INFO: Enabled downloader middlewares:
  10.  
    ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
  11.  
    'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
  12.  
    'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
  13.  
    'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
  14.  
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
  15.  
    'scrapy.downloadermiddlewares.retry.RetryMiddleware',
  16.  
    'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
  17.  
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
  18.  
    'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
  19.  
    'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
  20.  
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
  21.  
    'scrapy.downloadermiddlewares.stats.DownloaderStats']
  22.  
    2018-09-29 14:07:50 [scrapy.middleware] INFO: Enabled spider middlewares:
  23.  
    ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
  24.  
    'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
  25.  
    'scrapy.spidermiddlewares.referer.RefererMiddleware',
  26.  
    'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
  27.  
    'scrapy.spidermiddlewares.depth.DepthMiddleware']
  28.  
    2018-09-29 14:07:50 [scrapy.middleware] INFO: Enabled item pipelines:
  29.  
    []
  30.  
    2018-09-29 14:07:50 [scrapy.core.engine] INFO: Spider opened
  31.  
    2018-09-29 14:07:50 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
  32.  
    2018-09-29 14:07:50 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
  33.  
    2018-09-29 14:07:50 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.qunar.com/robots.txt> (referer: None)
  34.  
    2018-09-29 14:07:50 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.qunar.com/> (referer: None)
  35.  
    <Selector xpath='/html/head/title' data='<title>【去哪儿网】机票查询预订,酒店预订,旅游团购,度假搜索,门票预订-'>
  36.  
    2018-09-29 14:07:50 [scrapy.core.engine] INFO: Closing spider (finished)
  37.  
    2018-09-29 14:07:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
  38.  
    {'downloader/request_bytes': 498,
  39.  
    'downloader/request_count': 2,
  40.  
    'downloader/request_method_count/GET': 2,
  41.  
    'downloader/response_bytes': 23167,
  42.  
    'downloader/response_count': 2,
  43.  
    'downloader/response_status_count/200': 2,
  44.  
    'finish_reason': 'finished',
  45.  
    'finish_time': datetime.datetime(2018, 9, 29, 6, 7, 50, 801314),
  46.  
    'log_count/DEBUG': 3,
  47.  
    'log_count/INFO': 7,
  48.  
    'response_received_count': 2,
  49.  
    'scheduler/dequeued': 1,
  50.  
    'scheduler/dequeued/memory': 1,
  51.  
    'scheduler/enqueued': 1,
  52.  
    'scheduler/enqueued/memory': 1,
  53.  
    'start_time': datetime.datetime(2018, 9, 29, 6, 7, 50, 318350)}
  54.  
    2018-09-29 14:07:50 [scrapy.core.engine] INFO: Spider closed (finished)
  55.  
     
  56.  
    Process finished with exit code 0

嗯 这样说明Scrapy已经可以使用,下面就可以愉快的推进了任务了


相关教程