基于scrapy实现的简单蜘蛛采集程序

yipeiwu_com6年前Python基础

本文实例讲述了基于scrapy实现的简单蜘蛛采集程序。分享给大家供大家参考。具体如下:

# Standard Python library imports
# 3rd party imports
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
# My imports
from poetry_analysis.items import PoetryAnalysisItem
HTML_FILE_NAME = r'.+\.html'
class PoetryParser(object):
  """
  Provides common parsing method for poems formatted this one specific way.
  """
  date_pattern = r'(\d{2} \w{3,9} \d{4})'
 
  def parse_poem(self, response):
    hxs = HtmlXPathSelector(response)
    item = PoetryAnalysisItem()
    # All poetry text is in pre tags
    text = hxs.select('//pre/text()').extract()
    item['text'] = ''.join(text)
    item['url'] = response.url
    # head/title contains title - a poem by author
    title_text = hxs.select('//head/title/text()').extract()[0]
    item['title'], item['author'] = title_text.split(' - ')
    item['author'] = item['author'].replace('a poem by', '')
    for key in ['title', 'author']:
      item[key] = item[key].strip()
    item['date'] = hxs.select("//p[@class='small']/text()").re(date_pattern)
    return item
class PoetrySpider(CrawlSpider, PoetryParser):
  name = 'example.com_poetry'
  allowed_domains = ['www.example.com']
  root_path = 'someuser/poetry/'
  start_urls = ['http://www.example.com/someuser/poetry/recent/',
         'http://www.example.com/someuser/poetry/less_recent/']
  rules = [Rule(SgmlLinkExtractor(allow=[start_urls[0] + HTML_FILE_NAME]),
                  callback='parse_poem'),
       Rule(SgmlLinkExtractor(allow=[start_urls[1] + HTML_FILE_NAME]),
                  callback='parse_poem')]

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python脚本之一键移动自定格式文件方法实例

python脚本之一键移动自定格式文件方法实例

前言 尝试用python语言写脚本是好的开始,证明我们有了自动化的思想,这对优秀的程序开发人员是很重要的,电子计算机本来就是要减少重复工作的。 首先我们要用到python自带的一些包,p...

关于Python-faker的函数效果一览

tags faker 随机 虚拟 faker文档链接 代码程序: # -*- coding=utf-8 -*- import sys from faker import Factor...

Python环境Pillow( PIL )图像处理工具使用解析

前言 由于笔者近期的研究课题与图像后处理有关,需要通过图像处理工具对图像进行变换和处理,进而生成合适的训练图像数据。该系列文章即主要记录笔者在不同的环境下进行图像处理时常用的工具和库。在...

跟老齐学Python之编写类之二方法

跟老齐学Python之编写类之二方法

数据流转过程 除了在类中可以写这种函数之外,在类中还可以写别的函数,延续上一讲的例子: 复制代码 代码如下: #!/usr/bin/env python #coding:utf-8 cl...

python3学习笔记之多进程分布式小例子

python3学习笔记之多进程分布式小例子

最近一直跟着廖大在学Python,关于分布式进程的小例子挺有趣的,这里做个记录。 分布式进程 Python的multiprocessing模块不但支持多进程,其中managers子模块还...