基于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好书

不可错过的十本Python好书

以往的文章中小编已经给大家陆续推荐了很多的Python书籍,可以说品种齐全、本本经典了,不知道你是不是已经眼花缭乱,不知道该选择哪本好了呢?今天我来为大家分享十本不可错过的Python好...

Python语言快速上手学习方法

最近在学习Python,后面搞机器人项目需要用到,所以要快速上手,我使用的是PyCharm这个IDE,看起来就舒服,学习起来就有劲啦,作为一名有工作经验的老司机,我学习编程语言的方法不会...

Python os模块介绍

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd os.cur...

分析Python读取文件时的路径问题

分析Python读取文件时的路径问题

Python在读取文件内容时的路径问题,值得深究一下.我想讨论的重点还是在绝对路径上面.在这之前我们先看一下 1:相对路径 这张图演示了在相对路径下寻找查找指定文件.  ...

python使用urllib2提交http post请求的方法

本文实例讲述了python使用urllib2提交http post请求的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python #coding=utf-...