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

作者:pythoner 时间:2023-09-22 03:58:02 

本文实例讲述了基于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程序设计有所帮助。

标签:scrapy,蜘蛛,采集
0
投稿

猜你喜欢

  • mysql仿oracle的decode效果查询

    2024-01-12 22:04:00
  • 微软建议的ASP性能优化28条守则(6)

    2008-02-29 11:43:00
  • 深入浅出SQL教程之SELECT语句的自连接

    2009-08-30 15:17:00
  • MYSQL教程:检查数据表和修复数据表

    2009-03-11 15:24:00
  • TensorFlow低版本代码自动升级为1.0版本

    2023-08-12 02:02:24
  • ASP 多关键词查询实例代码

    2011-04-11 11:14:00
  • 亚马逊购物用户体验分析 (二)

    2009-10-25 12:48:00
  • JavaScript利用Canvas实现粒子动画倒计时

    2024-04-16 09:37:52
  • sqlserver 千万数量级分页存储过程代码

    2024-01-14 07:50:13
  • python中的None与NULL用法说明

    2022-01-01 13:59:15
  • python中列表元素连接方法join用法实例

    2023-01-20 17:49:31
  • Python个人博客程序开发实例用户验证功能

    2023-07-31 14:24:36
  • Pytorch加载数据集的方式总结及补充

    2023-02-15 17:14:37
  • SQL2008中通过DBCC OPENTRAN和会话查询事务

    2024-01-12 20:15:20
  • c#中过滤html的正则表达式

    2023-07-04 04:03:24
  • matplotlib之Font family [‘sans-serif‘] not found的问题解决

    2021-03-31 09:55:42
  • MySQL模糊查找like通配符使用(小白入门篇)

    2024-01-17 19:02:53
  • python中对开区间和闭区间的理解

    2022-02-09 17:47:29
  • GO的range具体使用

    2023-07-21 03:27:27
  • 如何利用Python识别图片中的文字

    2022-04-05 03:15:42
  • asp之家 网络编程 m.aspxhome.com