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

yipeiwu_com5年前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处理csv数据的方法

本文实例讲述了python处理csv数据的方法。分享给大家供大家参考。具体如下: Python代码: 复制代码 代码如下: #coding=utf-8 __author__ = 'deh...

pytorch::Dataloader中的迭代器和生成器应用详解

在使用pytorch训练模型,经常需要加载大量图片数据,因此pytorch提供了好用的数据加载工具Dataloader。 为了实现小批量循环读取大型数据集,在Dataloader类具体实...

Django 2.0版本的新特性抢先看!

前言 2017年12月2日,Django官方发布了2.0版本,成为多年来的第一次大版本提升,那么2.0对广大Django使用者有哪些变化和需要注意的地方呢? 一、Python兼容性 D...

Python操作redis和mongoDB的方法

一、操作redis redis是一个key-value存储系统,value的类型包括string(字符串),list(链表),set(集合),zset(有序集合),hash(哈希类型)。...

浅谈Python生成器generator之next和send的运行流程(详解)

对于普通的生成器,第一个next调用,相当于启动生成器,会从生成器函数的第一行代码开始执行,直到第一次执行完yield语句(第4行)后,跳出生成器函数。 然后第二个next调用,进入生成...