python的spider程序下载_基于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')]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值