Scrapy

一、Scrapy安装

不说了,装Ubuntu

在Windows上建环境就是SB

Xpath例子

1.新建项目

scrapy startproject tutorial

2.运行项目

scrapy crawl dmoz

3.打开测试窗口

scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/"

4.假设要匹配下面这段代码中的src

<div class="float-r">

<img src="/img/moz/obooksm.gif" width="84" height="55" alt="[Book Mozilla]">

 </div>

用下面这行

response.xpath("//div[@class = 'float-r']/img/@src").extract()

输出为

[u'/img/moz/obooksm.gif']


主代码

from scrapy.selector import HtmlXPathSelector

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

from scrapy.contrib.spiders import CrawlSpider, Rule

class MininovaSpider(CrawlSpider):

name = 'mininova.org'

allowed_domains = ['mininova.org']

start_urls = ['http://www.mininova.org/today']

rules = [Rule(SgmlLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')]

def parse_torrent(self, response):

x = HtmlXPathSelector(response)

torrent = TorrentItem()

torrent['url'] = response.url

torrent['name'] = x.select("//h1/text()").extract()

torrent['description'] = x.select("//div[@id='description']").extract()

torrent['size'] = x.select("//div[@id='info-left']/p[2]/text()[2]").extract()

return torrent

item代码

# -*- coding: utf-8 -*-

# Define here the models for your scraped items

#

# See documentation in:

# http://doc.scrapy.org/en/latest/topics/items.html

from scrapy.item import Item, Field

class TorrentItem(Item):

url = Field()

name = Field()

description = Field()

size = Field()


调用及保存为Json

scrapy crawl mininova.org -o scraped_data.json -t json

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • scrapy学习笔记(有示例版) 我的博客 scrapy学习笔记1.使用scrapy1.1创建工程1.2创建爬虫模...
    陈思煜阅读 14,371评论 4 46
  • 起因:学校项目实训,要求我们爬取招聘网站信息并对其进行分析,在此我和大家分享一下关于我爬取58同城招聘网站信息的过...
    www_Dicky阅读 7,410评论 4 9
  • 1.Scrapy的命令行命令 创建一个Scrapy工程终端输入: PyCharm 下直接运行 ScrapyScra...
    EnjoyWT阅读 8,353评论 0 1
  • (开学第一课) 1、陪女儿看《开学第一课》,其中有一个节目,钢琴小达人李俊杰和来自意大利的机器人TEL,藏在幕后,...
    南瓜是只猫阅读 3,226评论 0 1
  • 《大学肆年》目录 下了一天的雪终于停了下来,在这寒冷的冬季里蒋学文的嘴唇干燥的开裂。白婕急匆匆跑下楼来,没刹住脚步...
    帝恶道阅读 3,762评论 2 0